首页 >后端开发 >C++ >为什么`std::chrono::high_resolution_clock`的精度与测量值不同?

为什么`std::chrono::high_resolution_clock`的精度与测量值不同?

Patricia Arquette
Patricia Arquette原创
2024-11-09 06:14:02370浏览

Why Does `std::chrono::high_resolution_clock`'s Precision Differ from Measured Values?

std::chrono::high_resolution_clock精度为何与测量值不符?

问题:

在以下测试程序中,程序试图测量std::cout的执行时间,但得到的测量结果并不一致,始终是1 或2 微秒。这是因为std::chrono::high_resolution_clock的精度似乎不是 100 纳秒,或者测量std::cout执行时间的代码有问题。

#include <iostream>
#include <chrono>

using std::chrono::nanoseconds;
using std::chrono::duration_cast;

int main()
{
    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;
}

回答:

在Visual Studio 2012 中,std::chrono::high_resolution_clock 被定义为system_clock,这导致了较差的精度(大约1 毫秒)。为了获得更高的精度,可以使用以下自定义的高分辨率时钟:

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(&amp;frequency);
        return frequency.QuadPart;
    }();
}

HighResClock::time_point HighResClock::now()
{
    LARGE_INTEGER count;
    QueryPerformanceCounter(&amp;count);
    return time_point(duration(count.QuadPart * static_cast<rep>(period::den) / g_Frequency));
}

可以使用这个时钟来代替std::chrono::high_resolution_clock进行高精度时间测量。

以上是为什么`std::chrono::high_resolution_clock`的精度与测量值不同?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn