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
,分别是分数的分子和分母。