如何使用chrono为累加器计时器计算算法?

时间:2017-08-04 11:50:38

标签: c++ chrono

我的代码看起来像这样:

std::chrono::milliseconds total;
for (int i=0; i<max; i++) {
    auto start = std::chrono::high_resolution_clock::now();
    // some code I want to benchmark
    total += std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start);
    // some code I don't want to account for in my benchmark
}
std::cout << total.count() << std::endl;

当我运行此代码时,我有时会得到2,3或4甚至4。然而,其他时间,我得到一些随机结果,如139984111729355或-4800608627507701400。

为什么?

1 个答案:

答案 0 :(得分:4)

std::chrono::milliseconds total; // (1)
for (int i=0; i<max; i++) {
    auto start = std::chrono::high_resolution_clock::now();
    // some code I want to benchmark
    total += std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start);
    // some code I don't want to account for in my benchmark
}
std::cout << total.count() << std::endl;

This is a perfectly valid pattern, but the problem that your total variable at (1) is uninitialised. If you replace it with

std::chrono::milliseconds total{};

then it should work as intended.