首页  >  文章  >  后端开发  >  为什么 Visual Studio 2012 中的 std::chrono::high_resolution_clock 报告的分辨率比观察到的测量值更高?

为什么 Visual Studio 2012 中的 std::chrono::high_resolution_clock 报告的分辨率比观察到的测量值更高?

Susan Sarandon
Susan Sarandon原创
2024-11-13 14:35:03397浏览

Why does std::chrono::high_resolution_clock in Visual Studio 2012 report a higher resolution than observed measurements?

Inconsistent Measurement Accuracy with std::chrono::high_resolution_clock

Question:

In the given test program, the std::chrono::high_resolution_clock reports a resolution of 100 nanoseconds, but the measured time taken by std::cout consistently exceeds 1 microsecond. Why does the expected resolution not match the observed measurements?

Answer:

If Visual Studio 2012 is being used, the std::chrono::high_resolution_clock is typedef'd to system_clock, which has a limited resolution of approximately 1 millisecond. This discrepancy is what causes the observed inconsistency.

Resolution:

To obtain high-resolution timing in Visual Studio 2012, an alternative clock that utilizes QueryPerformanceCounter should be employed. The following code provides an example:

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));
}

This HighResClock can be used interchangeably with standard clocks, providing the necessary high-resolution timing functionality.

以上是为什么 Visual Studio 2012 中的 std::chrono::high_resolution_clock 报告的分辨率比观察到的测量值更高?的详细内容。更多信息请关注PHP中文网其他相关文章!

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