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.
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!