timer accuracy: c clock( ) vs. WinAPI's QPC or timeGetTime( )

c, c++, timer, winapi

Solution

You'll need to distinguish accuracy, resolution and latency.

clock(), GetTickCount and timeGetTime() are derived from a calibrated hardware clock. Resolution is not great, they are driven by the clock tick interrupt which ticks by default 64 times per second or once every 15.625 msec. You can use timeBeginPeriod() to drive that down to 1.0 msec. Accuracy is very good, the clock is calibrated from a NTP server, you can usually count on it not being off more than a second over a month.

QPC has a much higher resolution, always better than one microsecond and as little as half a nanosecond on some machines. It however has poor accuracy, the clock source is a frequency picked up from the chipset somewhere. It is not calibrated and has typical electronic tolerances. Use it only to time short intervals.

Latency is the most important factor when you deal with timing. You have no use for a highly accurate timing source if you can't read it fast enough. And that's always an issue when you run code in user mode on a protected mode operating system. Which always has code that runs with higher priority than your code. Particularly device drivers are trouble-makers, video and audio drivers in particular. Your code is also subjected to being swapped out of RAM, requiring a page-fault to get loaded back. On a heavily loaded machine, not being able to run your code for hundreds of milliseconds is not unusual. You'll need to factor this failure mode into your design. If you need guaranteed sub-millisecond accuracy then only a kernel thread with real-time priority can give you that.

A pretty decent timer is the multi-media timer you get from timeSetEvent(). It was designed to provide good service for the kind of programs that require a reliable timer. You can make it tick at 1 msec, it will catch up with delays when possible. Do note that it is an asynchronous timer, the callback is made on a separate worker thread so you have to be careful taking care of proper threading synchronization.

Problem

I'd like to characterize the accuracy of a software timer. I'm not concerned so much about HOW accurate it is, but do need to know WHAT the accuracy is. I've investigated c function clock(), and WinAPI's function QPC and timeGetTime, and I know that they're all hardware dependent. I'm measuring a process that could take around 5-10 seconds, and my requirements are simple: I only need 0.1 second precision (resolution). But I do need to know what the accuracy is, worst-case. while more accuracy would be preferred, I would rather know that the accuracy was poor (500ms) and account for it, than to believe that the accuracy was better (1 mS) but not be able to document it. Does anyone have suggestions on how to characterize software clock accuracy? Thanks

Original source

Related problems