c++ - 如何获得 high_resolution_clock 的精度?

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

https://stackoverflow.com/questions/8386128/

相关文章:

c++ - 如何以跨平台的方式获取(几乎)唯一的系统标识符?

c++ - 有没有办法在 Visual Studio 中获取某些 c++ 函数的调用图?

c++ - 如何在编译时检查两种类型是否相同(如果它与 Boost strong typedef 一

c++ - 使用 boost::graph 获取特定边缘

c++ - 如何在互斥锁中优先考虑特权线程?

c++ - 对两个对应的数组进行排序

c++ - #include 在查找预编译头文件时跳过 -- 查找预编译头文件时文件意外结束

c++ - 类成员和显式堆栈/堆分配

c++ - 如何检查 STL 迭代器是否指向任何东西?

c++ - Visual Studio 可以在重建前提示吗?