Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ high precision time measurement in Windows

Tags:

c++

c

windows

I'm interested in measuring a specific point in time down to the nanosecond using C++ in Windows. Is this possible? If it isn't, is it possible to get the specific time in microseconds at least?. Any library should do, unless I suppose it's possible with managed code. thanks

like image 936
Kelly Elton Avatar asked Dec 01 '09 11:12

Kelly Elton


People also ask

What is system's high resolution time?

4 High Resolution Time This specification defines an interface that provides the current time in sub-millisecond resolution and such that it is not subject to system clock skew or adjustments.

What is QueryPerformanceCounter?

QueryPerformanceCounter() is used to get the current elapsed ticks, and QueryPerformanceFrequency() is used to get the number of ticks per second, which is used to convert ticks to the actual time. Here is a usage of QueryPerformanceCounter() for measuring elapsed time.

What is resolution of timer?

Timer resolution is the smallest unit of time that can be accurately measured by that timer. Timer resolution for the CPU (which is the RTC or Real Time Clock resolution) differs from that of the API made available to the programmer by the operating system.

What is query performance frequency?

QueryPerformanceFrequency function (profileapi.Retrieves the frequency of the performance counter. The frequency of the performance counter is fixed at system boot and is consistent across all processors. Therefore, the frequency need only be queried upon application initialization, and the result can be cached.


1 Answers

If you have a threaded application running on a multicore computer QueryPerformanceCounter can (and will) return different values depending on which core the code is executing on. See this MSDN article. (rdtsc has the same problem)

This is not just a theoretical problem; we ran into it with our application and had to conclude that the only reliable time source is timeGetTime which only has ms precision (which fortunately was sufficient in our case). We also tried fixating the thread affinity for our threads to guarantee that each thread always got a consistent value from QueryPerformanceCounter, this worked but it absolutely killed the performance in the application.

To sum things up there isn't a reliable timer on windows that can be used to time thing with micro second precision (at least not when running on a multicore computer).

like image 158
Andreas Brinck Avatar answered Sep 27 '22 20:09

Andreas Brinck