让我通过这个测试程序问我的问题:
#include <iostream>
#include <chrono>
using std::chrono::nanoseconds;
using std::chrono::duration_cast;
int main(int argc, char* argv[])
{
std::cout << "resolution (nano) = " << (double) std::chrono::high_resolution_clock::period::num
/ std::chrono::high_resolution_clock::period::den * 1000 * 1000 * 1000 << std::endl;
auto t1 = std::chrono::high_resolution_clock::now();
std::cout << "how much nanoseconds std::cout takes?" << std::endl;
auto t2 = std::chrono::high_resolution_clock::now();
auto diff = t2-t1;
nanoseconds ns = duration_cast<nanoseconds>(diff);
std::cout << "std::cout takes " << ns.count() << " nanoseconds" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我机器上的输出:
分辨率(纳米)= 100
std :: cout需要多少纳秒? …
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";
}
Run Code Online (Sandbox Code Playgroud)