C++11 定义了high_resolution_clock
,它的成员类型有period
和rep
。但我不知道如何获得那个时钟的精确度。
或者,如果我可能无法达到精确度,我是否可以以某种方式至少获得滴答之间最小可表示持续时间的纳秒计数?可能使用 period
?
#include <iostream>
#include <chrono>
void printPrec() {
std::chrono::high_resolution_clock::rep x = 1;
// this is not the correct way to initialize 'period':
//high_resolution_clock::period y = 1;
std::cout << "The smallest period is "
<< /* what to do with 'x' or 'y' here? */
<< " nanos\n";
}
最佳答案
可表示的最小持续时间是 high_resolution_clock::period::num/high_resolution_clock::period::den
秒。你可以这样打印:
std::cout << (double) std::chrono::high_resolution_clock::period::num
/ std::chrono::high_resolution_clock::period::den;
这是为什么?时钟的 ::period
成员定义为“时钟的刻度周期,以秒为单位”。它是 std::ratio
的一个特化,它是一个在编译时表示比率的模板。它提供了两个整数常量:num
和 den
,分别是分数的分子和分母。
https://stackoverflow.com/questions/8386128/