c++ - vector push_back() with reserve() 运行缓慢

标签 c++

当使用 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/

相关文章:

c++ - std::string 的 operator[] 和 const operator[] 的区别

c++ - 模板类特化的C++内联或非内联声明

c++ - C++ 中的指针,原始内存操作

c++ - 在不同的着色器中使用相同的常量缓冲区

c++ - 添加到 QList 的 C++ 类的范围是什么

c++ - 错误 LNK2019 : unresolved external symbol error

c++ - 解除分配后删除(悬挂)指针的 vector 元素

c++ - 创建一个非线程安全的 shared_ptr

c++ - CreateFile 返回错误 INVALID_HANDLE_VALUE(对于 COM 端口),GetLastError 返回 "can' t 找到指定的文件”

c++ - visual studio 和 gcc 的 const 引用语法区别