Home > Backend Development > C++ > body text

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

Susan Sarandon
Release: 2024-11-13 14:35:03
Original
392 people have browsed it

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();
};
Copy after login

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));
}
Copy after login

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

The above is the detailed content of Why does std::chrono::high_resolution_clock in Visual Studio 2012 report a higher resolution than observed measurements?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template