C++ 11定义了high_resolution_clock,其成员类型为periodrep。但是我不知道如何获得该时钟的精度

或者,如果我可能达不到精度,我能否以某种方式至少获得滴答之间最小可表示持续时间的纳秒计数?大概使用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的一种特殊形式,它是一个模板,用于表示编译时的比率。它提供了两个整数常量:numden,分别是分数的分子和分母。

10-01 23:53
查看更多