std::chrono::high_resolution_clock 的分辨率与测量值不符

Resolution of std::chrono::high_resolution_clock doesn't correspond to measurements

本文关键字:测量 分辨率 clock chrono high resolution std      更新时间:2023-10-16

让我用这个测试程序来问我的问题:

#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 many nanoseconds does std::cout take?" << 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;
}

我的机器上的输出:

分辨率(nano) = 100

std::cout需要多少纳秒?

std::cout占用1000200纳秒

我收到100020010003001000400100050010006002000600作为结果(= 1或2微秒)。显然,要么std::chrono的分辨率是,而不是 100纳秒,要么是,我测量std::cout的时间的方法是错误的。(为什么我从来没有收到1到2微秒之间的东西,例如1500000 ?)

我需要一个高分辨率的定时器在c++。操作系统本身提供了一个高分辨率计时器,因为我可以在同一台机器上使用c# Stopwatch类以微秒级的精度进行测量。所以我只需要正确使用操作系统的高分辨率计时器!

我如何修正我的程序以产生预期的结果?

我猜你用的是Visual Studio 2012。如果不是,忽略这个答案。Visual Studio 2012 typedefhigh_resolution_clocksystem_clock。可悲的是,这意味着它的精度很差(大约1毫秒)。我写了一个更好的高分辨率时钟,使用QueryPerformanceCounter在Visual Studio 2012中使用…

HighResClock.h:

    struct HighResClock
    {
        typedef long long                              rep;
        typedef std::nano                              period;
        typedef std::chrono::duration<rep, period>     duration;
        typedef std::chrono::time_point<HighResClock>  time_point;
        static const bool is_steady = true;
        static time_point now();
    };

HighResClock.cpp:

namespace
{
    const long long g_Frequency = []() -> long long
    {
        LARGE_INTEGER frequency;
        QueryPerformanceFrequency(&frequency);
        return frequency.QuadPart;
    }();
}
HighResClock::time_point HighResClock::now()
{
    LARGE_INTEGER count;
    QueryPerformanceCounter(&count);
    return time_point(duration(count.QuadPart * static_cast<rep>(period::den) / g_Frequency));
}

(我省略了一个assert和#if来查看它是否在Visual Studio 2012上从上面的代码编译)

你可以在任何地方使用这个时钟,就像使用标准时钟一样。

时钟的分辨率不一定与时钟使用的数据类型可以表示的最小持续时间相同。在这种情况下,您的实现使用的数据类型可以表示小到100纳秒的持续时间,但底层时钟实际上没有这样的分辨率。


Visual Studio的high_resolution_clock的低分辨率已经是一个问题好几年了。微软的c++标准库维护者Stephan T. Lavavej表示,通过使用QueryPerformanceCounter(), Visual Studio 2015已经修复了这个问题。

也许实现不实现更高分辨率的计时器?

似乎你正在使用Windows(你提到c#),所以如果你使用计时器,你确实使用Windows,你可以使用queryperformancfrequency和QueryPerformanceCounter。