当使用 visual c++2010 express 和 WinXP 运行以下代码时,“for 循环”始终执行 如下:
Read 25000 lines in 31ms, Read 25000 lines in 62ms, Read 25000 lines in 46ms, Read 25000 lines in 62ms, Read 25000 lines in 46ms, Read 25000 lines in 46ms
但是,当我在 Windows 7 家庭版上使用 visual c++2010 express 进行编译时,for 循环执行如下:
Read 25000 lines in 62ms, Read 25000 lines in 530ms, Read 25000 lines in 514ms, Read 25000 lines in 514ms, Read 25000 lines in 514ms, Read 25000 lines in 530ms
我试图找出为什么“for 循环”在 Windows 7 上第一次运行 t 毫秒,但随后跳转到 10 x t 毫秒以进行后续运行。而在 XP 上它始终运行 t 毫秒。它可能是 Windows 7 构建/设置的特定内容或代码中的一些基本内容。
我最近开始编写 C++ 程序,非常感谢您帮助我了解 Windows 7 环境中发生的事情。
#include <iostream>
#include <string>
#include <vector>
#include "Elapsed.h"
using namespace std;
void readfile(){
Elapsed time1;
vector<string> lines;
lines.reserve(50000);
string s = "this is a string this is a longer string ";
for(int i = 0; i<25000; i++) lines.push_back(s);
cout<<"Read "<<lines.size()<<" lines in "<<time1().total_milliseconds()<<"ms\n";
}
int main(){
readfile();
readfile();
readfile();
readfile();
readfile();
readfile();
system("PAUSE");
}
#include <boost/date_time.hpp>
// Purpose: track elapsed time from constructor or reset
class Elapsed {
boost::posix_time::ptime m_when;
public:
static boost::posix_time::ptime now(){return boost::posix_time::microsec_clock::universal_time();}
Elapsed(): m_when( now() )
{
} // end constructor
void reset() { m_when = now(); }
boost::posix_time::time_duration operator()() const {
return now() - m_when;
} //end operator()
};// end class
最佳答案
你应该这样计算你的时间:
boost::posix_time::time_duration span = time1();
cout << "Read " << lines.size() << " lines in "<<
span.total_milliseconds() << "ms\n";
请注意 operator<<
不包括序列点,因此您可以在计时器中包括一些到 cout
的输出,并且 IO 时序可能非常不可预测。
关于c++ - vector push_back() with reserve() 运行缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15301850/