C++11 High Resolution Clock Time_Point – How to Print

c++c++-chronoc++11

How do I print out a time_point when the time_point is obtained from high_resolution_clock?

timestamp = std::chrono::high_resolution_clock::now();
std::time_t now = std::chrono::system_clock::to_time_t(timestamp);
std::cout << std::ctime(&now) << std::endl;

I get the following error message when compiling:

error: no viable conversion from 'time_point<class std::__1::chrono::steady_clock, duration<[...], ratio<[...], 1000000000>>>' to 'const time_point<class std::__1::chrono::system_clock, duration<[...], ratio<[...], 1000000>>>'
        time_t tt = std::chrono::system_clock::to_time_t(timestamp);

Best Answer

There is no truly graceful way to do this. high_resolution_clock is not known to be related to UTC, or any other calendar. One thing you can portably do is output its current duration from its unspecified epoch, along with the units of that duration:

#include <chrono>
#include <iostream>

int
main()
{
    using Clock = std::chrono::high_resolution_clock;
    constexpr auto num = Clock::period::num;
    constexpr auto den = Clock::period::den;
    std::cout << Clock::now().time_since_epoch().count()
              << " [" << num << '/' << den << "] units since epoch\n";
}

Which for me outputs:

516583779589531 [1/1000000000] units since epoch

which means it is 516583779589531 nanoseconds (or 516,583.779589531 seconds) since the epoch of this clock on my machine. On my machine this translates to: my machine has been booted up for nearly 6 days. But that translation is not portable.

Ah! And I note from your error message that you are using libc++. If you are also on OS X, then we have the same definition of high_resolution_clock: It counts nanoseconds since your computer was booted.