Home >Backend Development >C++ >Why Does `std::chrono::high_resolution_clock` Show Discrepancies Despite Nanosecond Resolution?

Why Does `std::chrono::high_resolution_clock` Show Discrepancies Despite Nanosecond Resolution?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 19:08:02358browse

Why Does `std::chrono::high_resolution_clock` Show Discrepancies Despite Nanosecond Resolution?

std::chrono::high_resolution_clock Resolution Discrepancy

Despite specifying a nanosecond resolution for the std::chrono::high_resolution_clock, discrepancies arise when measuring time intervals. This can be seen in the provided test program where the reported time taken by std::cout is not precisely within the expected resolution range.

Resolving the Discrepancy

The cause of this discrepancy lies in the implementation of std::chrono::high_resolution_clock on Visual Studio 2012. Under this environment, high_resolution_clock is defined as an alias for system_clock, which has a resolution around 1 millisecond.

Fix for Visual Studio 2012

To obtain a truly high-resolution timer on Visual Studio 2012, a custom high-resolution clock implementation is recommended:

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

Usage of Custom Clock

The custom HighResClock can be used in place of std::chrono::high_resolution_clock with the same functionality. By utilizing QueryPerformanceCounter directly, it provides accurate high-resolution timing.

The above is the detailed content of Why Does `std::chrono::high_resolution_clock` Show Discrepancies Despite Nanosecond Resolution?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn