Resolution Discrepancy in std::chrono::high_resolution_clock
In a test program designed to measure the time taken by std::cout, the output reveals a consistently high deviation from the expected 100 nanosecond resolution of std::chrono::high_resolution_clock. Instead, the measured duration ranges from 1 to 2 microseconds. This discrepancy raises questions about the reported resolution and the accuracy of the time measurement method.
Factors Affecting Resolution
The resolution of a clock, as reported by its period, is the smallest unit of time it can measure. While Visual Studio 2012 includes a high-resolution clock, it unfortunately falls short in precision, typically exhibiting a resolution of around 1 millisecond. This is attributed to the fact that Visual Studio 2012 redefines high_resolution_clock to system_clock, which inherently has lower precision.
Alternative High-Resolution Clock for Visual Studio 2012
To address this limitation, a more accurate high-resolution clock can be implemented using the QueryPerformanceCounter function provided by the operating system. The HighResClock class provided below addresses this issue by utilizing QueryPerformanceCounter to offer a reliable clock with microsecond-level precision:
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() { LARGE_INTEGER count; QueryPerformanceCounter(&count); return time_point(duration(count.QuadPart * static_cast<rep>(period::den) / g_Frequency)); } }; namespace { const long long g_Frequency = []() -> long long { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); return frequency.QuadPart; }(); }
This alternative clock can be seamlessly integrated into existing code, allowing high-resolution time measurement even within the constraints of Visual Studio 2012.
The above is the detailed content of Why Does std::chrono::high_resolution_clock Report Lower Resolution Than Expected in Visual Studio 2012?. For more information, please follow other related articles on the PHP Chinese website!