Search code examples
c++c++11query-performanceperformancecounterc++-chrono

Can Clock with direct QueryPerformanceCounter value be conforming to C++ Standard?


Assuming I want to create Clock with direct QueryPerformanceCounter Windows API result. QueryPerformanceCounter Windows API returns some counter that should be divided by QueryPerformanceFrequency result, thus producing time in seconds.

Usually Clock based on QueryPerformanceCounter would immediately convert result to some units by multiplying by some period and dividing by QueryPerformanceFrequency. This is how steady_clock could be implemented on Windows.

But suppose that for performance reasons I want to avoid division until really needed. So time_point is direct QueryPerformanceCounter value, and duration is the difference of such. And I can perform arithmetic and comparison on those values most of the time, converting to some normal duration or time_point only the final result.

I'm sure it is possible. My question is: will such Clock be fully compatible with standard Clock.


Solution

  • It won't be fully compatible with the standard Clock Requirements. But it will compile and do what you want, most of the time. The part that doesn't conform is that you will have to specify something for the period that your time_point is based on. And that something won't necessarily correspond to physical time units.

    This won't matter until you subtract two of these time_points, get a duration, and then compare that duration with something that does represent physical time. Then you'll get run-time garbage.

    Also if you use such a time_point in sleep_until, or wait_until, then your program won't sleep or wait for the intended time.

    Here is an example chrono clock based on QueryPerformanceCounter that does nail down the physical units with QueryPerformanceFrequency: https://stackoverflow.com/a/15755865/576911