How to get the precision of high_resolution_clock?

左心房为你撑大大i 提交于 2019-11-27 21:11:06

The minimum representable duration is high_resolution_clock::period::num / high_resolution_clock::period::den seconds. You can print it like this:

std::cout << (double) std::chrono::high_resolution_clock::period::num
             / std::chrono::high_resolution_clock::period::den;

Why is this? A clock's ::period member is defined as "The tick period of the clock in seconds." It is a specialization of std::ratio which is a template to represent ratios at compile-time. It provides two integral constants: num and den, the numerator and denominator of a fraction, respectively.

I upvoted R. Martinho Fernandes's answer because I believe it offers the clearest, most straightforward answer to the question. However I wanted to add a little code that showed a little more <chrono> functionality and that addressed this part of the OP's question:

can I somehow at least get a count in nanoseconds of the minimum representable time duration between ticks?

And it is impractical to put this much information into a comment. But I otherwise regard this answer as a supportive comment to R. Martinho Fernandes's answer.

First the code, and then the explanation:

#include <iostream>
#include <chrono>

template <class Clock>
void
display_precision()
{
    typedef std::chrono::duration<double, std::nano> NS;
    NS ns = typename Clock::duration(1);
    std::cout << ns.count() << " ns\n";
}

int main()
{
    display_precision<std::chrono::high_resolution_clock>();
    display_precision<std::chrono::system_clock>();
}

First I created a nanosecond that is using a double as the representation (NS). I used double just in case I needed to show fractions of a nanosecond (e.g. 0.5 ns).

Next, every clock has a nested type named duration. This is a chrono::duration that will have the same std::ratio, and thus the same num and den as pointed out in R. Martinho Fernandes's answer. One of those durations, converted to NS will give us how many nanoseconds in one clock tick of Clock. And that value can be extracted from the duration with the count() member function.

For me this program prints out:

1 ns
1000 ns

An std::ratio type representing the tick period of the clock, in seconds.Defined in namespace std::chrono

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