C ++ 11如何打印出高分辨率的时钟time_point [英] C++11 how to print out high resolution clock time_point

查看:1623
本文介绍了C ++ 11如何打印出高分辨率的时钟time_point的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当从high_resolution_clock获取time_point时,如何打印time_point?

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


推荐答案

没有真正优雅的方法。 high_resolution_clock 不知道与UTC或任何其他日历相关。你可以移植的做法是从其未指定的时期输出当前持续时间,以及持续时间的单位:

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

这对我输出:

516583779589531 [1/1000000000] units since epoch

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

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.

啊!我们从您的错误讯息中注意到您正在使用 libc ++ 。如果你也是在OS X上,那么我们有同样的定义 high_resolution_clock :从计算机引导以来计算纳秒。

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.

这篇关于C ++ 11如何打印出高分辨率的时钟time_point的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆