user1546022
user1546022

Reputation: 183

How to use chrono to time an algorithm with an accumulator timer?

My code looks something like this:

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;

When I run this code I sometimes get 2, 3 and even 4 as a result. Other times however, I get some random result like 139984111729355 or -4800608627507701400.

Why is that?

Upvotes: 1

Views: 579

Answers (1)

Tristan Brindle
Tristan Brindle

Reputation: 16824

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.

Upvotes: 4

Related Questions