Reputation: 33
A huge amount has been said about high resolution timers on stackoverflow. But it's clear that the solution is a bit of a moving target and best practices are changing.
I need to create a high resolution timer that has a callback every 10ms to achieve a consistent 100Hz. The target platform is Windows 7 and later.
This exact question was asked in 2009, but I believe things have probably moved on.
Multimedia timers looked to be a great solution, but MSDN says they are depreciated, replaced with CreateTimerQueueTimer. But other answers on stackoverflow suggest that CreateTimerQueue timer is not as accurate as timeSetEvent.
All answers do consistently point out the requirement for setting the windows timer resolution to a low value using timeBeginPeriod.
So with all that said, what is the best approach to achieve the above desired goal in C today.
Upvotes: 3
Views: 3049
Reputation: 374
Are you willing to burn CPU as you go? Call QueryPerformanceCounter() in a busy loop. You will get microsecond precision, with appropriate detrimental effect on battery life. You can also take it to eleven with jacking up your process priority class to REALTIME_PRIORITY_CLASS and worker thread's priority to THREAD_PRIORITY_TIME_CRITICAL (or a notch or two lower). There are of course negative consequences for doing such things.
Upvotes: 0
Reputation: 942308
but MSDN says they are depreciated
It is pretty important to be able to read between the lines when you see a deprecation warning like this. Yes, most certainly Microsoft would like everybody to stop using multimedia timers. They are heavily abused and are very bad for business. Actually getting programmers to stop using them is however a pipe dream, CreateTimerQueueTimer() is not an alternative.
Bad for business because Microsoft likes to be competitive in mobile computing. And multimedia timers are a very poor match, they are murder on battery life. Most programs that use them jack up the clock interrupt rate the maximum allowed, 1000 times per second. With a backdoor to get to 2000. And it is very hard to stop them from doing that, especially when their competitors give their software away for free. They have no incentive whatsoever to fix that problem since it makes their mobile OS look good. And Microsoft can't kill very popular apps like that.
Microsoft also has a mobile OS, exposed through the WinRT api. Where that deprecation is rock-hard, you cannot get your app approved by the Store validation procedure when you use those timers. But it doesn't get much use, their customers like to keep using their desktop apps.
If you want a 100 Hz update rate then you have use use timeBeginPeriod() and timeSetEvent(), there is no other way. And avoid WinRT. Since it is actually only 1.5 times worse than the default, there is no appreciable reason to worry about power consumption. Set laser to stun and use what works.
Upvotes: 4