C ++ 11如何打印出高分辨率时钟time_point

时间:2014-09-30 18:53:36

标签: c++ c++11 chrono

如何从high_resolution_clock获取time_point时打印出time_point?

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;

编译时收到以下错误消息:

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

3 个答案:

答案 0 :(得分:14)

没有真正优雅的方式来做到这一点。不知道high_resolution_clock与UTC或任何其他日历有关。你可以做的一件事是从未指定的时期输出当前的持续时间,以及该持续时间的单位:

#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";
}

对我而言输出:

516583779589531 [1/1000000000] units since epoch

这意味着自我机器上的这个时钟的纪元以来它是516583779589531纳秒(或516,583.779589531秒)。在我的机器上,这意味着:我的机器已经启动了将近6天。但是这种翻译不可移植。

啊!我从您的错误消息中注意到您正在使用libc++。如果您也使用OS X,那么我们对high_resolution_clock的定义相同:自计算机启动以来它的计数为纳秒。

答案 1 :(得分:3)

至少在我阅读的时候,意图是std::high_resolution_clock可以被定义为类似CPU的时间戳计数器的包装器,它只是一个注册表,而且#39} ; s每个CPU时钟周期递增。

不一定是这种情况(当前系统不断修改CPU时钟频率可能不是一个好主意),但其他类似的时钟也是支持的。

底线:绝对时间和高分辨率时钟之间可能没有已知关系,因此它的确定义只是为了产生持续时间,而不是绝对时间。

答案 2 :(得分:0)

从任何时钟时间点到 time_t 的转换由 this post 提供。

相关问题