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中文网其他相关文章!