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

前端 未结 2 687
长情又很酷
长情又很酷 2020-12-31 08:22

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_         


        
相关标签:
2条回答
  • 2020-12-31 08:44

    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.

    0 讨论(0)
  • 2020-12-31 08:47

    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.

    0 讨论(0)
提交回复
热议问题