C++11 how to print out high resolution clock time_point

血红的双手。 提交于 2019-12-18 15:28:23

问题


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);

回答1:


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.




回答2:


At least as I read things, the intent is that std::high_resolution_clock could be defined as a wrapper around something like a CPU's time-stamp counter, that's simply a register that's incremented every CPU clock cycle.

That's not necessarily the case (and with current systems constantly modifying CPU clock frequency probably a poor idea), but other similar clocks are also intended to be supported.

Bottom line: there may not be a known relationship between absolute time and the high-resolution clock, so it's really defined only to produce durations, not absolute times.



来源:https://stackoverflow.com/questions/26128035/c11-how-to-print-out-high-resolution-clock-time-point

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!