矢量push_back()与reserve()运行缓慢

时间:2013-03-08 19:33:40

标签: c++

使用visual c ++ 2010 express和WinXP运行以下代码时,'for循环'始终执行 如下:

  

读31000行25000行,62ms读25000行,46ms读25000行,62ms读25000行,46ms读25000行,46ms读25000行

然而,当我在Windows 7 Home Edition上使用visual c ++ 2010 express进行编译时,for循环执行如下:

  

在62ms读取25000行,在530ms读取25000行,在514ms读取25000行,在514ms读取25000行,在514ms读取25000行,在530ms读取25000行

我正在试图弄清楚为什么'for loop'在Windows 7上第一次运行msecs,然后为后续运行跳转到10 x t msecs。而在XP上,它一直运行t msecs。它可能是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

1 个答案:

答案 0 :(得分:1)

你应该像这样计算你的时间:

boost::posix_time::time_duration span = time1();
cout << "Read " << lines.size() << " lines in "<< 
     span.total_milliseconds() << "ms\n";

请注意,operator<<不包含序列点,因此您可以在计时器中包含一些输出到cout,并且IO时序可能非常不可预测。

相关问题