Reputation: 183
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
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