[英]vector push_back() with reserve() running slow
使用Visual c ++ 2010 express和WinXP運行以下代碼時,“ for循環”的執行情況如下:
在31毫秒內讀取25000線,在62毫秒內讀取25000線,在46毫秒內讀取25000線,在62毫秒內讀取25000線,在46毫秒內讀取25000線,在46毫秒內讀取25000線
但是,當我在Windows 7 Home Edition上使用Visual c ++ 2010 express進行編譯時,for循環執行如下:
以62ms讀取25000條線,以530ms讀取25000條線,以514ms讀取25000條線,以514ms讀取25000條線,以514ms讀取25000條線,以530ms讀取25000條線
我試圖弄清楚為什么“ for循環”第一次在Windows 7上運行t毫秒,但隨后跳到10 xt毫秒以進行后續運行。 而在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時序可能非常不可預測。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.