Mark
Mark

Reputation: 25

What is the maximum time interval chrono can measure in C++?

I'm quiet experienced in programming, but new to C++. I'm trying to measure the time it takes to run a code. In the future I might write code that can take hours/days to finish itself. Therefore it is important for me to know the limits of the chrono time measurement. Accuracy in milliseconds should be sufficient.

What is the maximum time I can measure?

I have used the following code, please let me know if this can be improved:

#include <chrono> 
using namespace std::chrono;

auto start = high_resolution_clock::now();

// calculations here

auto finish = high_resolution_clock::now();

duration<double> elapsed = finish - start; // elapsed time in seconds
cout << elapsed.count();

Upvotes: 2

Views: 1961

Answers (2)

Howard Hinnant
Howard Hinnant

Reputation: 218770

Here's an informative little HelloWorld:

#include <chrono>
#include <iostream>

int
main()
{
    using namespace std::chrono;
    using namespace std;

    using years = duration<double, ratio_multiply<ratio<86'400>, ratio<146'097, 400>>>;
    cout << years{high_resolution_clock::time_point::max() - 
                  high_resolution_clock::now()}.count()
         << " years until overflow\n";
}

I first create a double-based years duration so that the output is easy to read. Then I subtract now() from the time_point's max(), convert that to years and print it out.

For me this just output:

292.256 years until overflow

Upvotes: 1

matovitch
matovitch

Reputation: 1284

std::chrono::milliseconds is guaranteed to be stored on a underlying signed integer of at least 45 bits which means that if your elapsed duration is less than 544 years you should be fine.

Source: https://en.cppreference.com/w/cpp/chrono/duration

Edit: As orlp pointed out you might have some issues if/when the clock overflow (but I do not see any mention of it on cppreference).

Also,

The high_resolution_clock is not implemented consistently across different standard library implementations, and its use should be avoided.

[...]

Generally one should just use std::chrono::steady_clock or std::chrono::system_clock directly instead of std::chrono::high_resolution_clock: use steady_clock for duration measurements, and system_clock for wall-clock time.

Upvotes: 1

Related Questions