ITTONE Création des applications Web

winapi – Do I have to call timeBeginPeriod before timeSetEvent when using Windows multimedia timers?

Do I have to call timeBeginPeriod before timeSetEvent?


Microsoft’s documentation is misleading. Indeed, the documentation for timeBeginPeriod states:

Call this function immediately before using timer services… call the timeEndPeriod function immediately after you are finished using timer services…

Which has lead to the ubiquitous coding pattern:

call timeBeginPeriod
call timeSetEvent
do stuff...
call timeKillEvent
call timeEndPeriod

In this pattern, the calls to timeBeginPeriod and timeEndPeriod are unnecessary. Mike Wasson, who wrote SDK documentation for Windows multimedia APIs, clarifies this in a forum post:

Internally, timeSetEvent calls timeBeginPeriod, so the uResolution parameter in timeSetEvent acts just like timeBeginPeriod. When the timer is cancelled (either by calling timeKillEvent for a periodic timer, or after a one-shot timer expires), internally it calls timeEndPeriod.

My evidence-based recommendation

Unless there is good reason, timeBeginPeriod/timeEndPeriod should not be called when using timeSetEvent/timeKillEvent. Doing so only increases the risk of timeBeginPeriod being called earlier than necessary, or timeEndPeriod being called later than necessary, or worse still timeEndPeriod not being called at all (a risk that absolutely exists in complex code using multiple timers). In all these cases system performance and power usage can be negatively impacted if high resolution timing has been requested:

Setting a higher resolution can improve the accuracy of time-out intervals in wait functions. However, it can also reduce overall system performance, because the thread scheduler switches tasks more often. High resolutions can also prevent the CPU power management system from entering power-saving modes.


Microsoft warns that timeSetEvent is obsolete and recommends using CreateTimerQueueTimer. However, this alternative timer might not be suitable for precision timing:

Callback functions are queued to the thread pool. These threads are subject to scheduling delays, so the timing can vary depending on what else is happening in the application or the system.

So it seems that, for now, the “obsolete” timeSetEvent function is still the only practical option for precision event/callback-based timing.

Windows 10 2004 April 2020 attempts to ameliorate some of the system-wide impacts of applications that use multimedia timers at high resolutions. The linked article contains important information for folks who use timeBeginPeriod for its system-wide “side-effect” benefit e.g. higher resolution for Wait and Sleep functions.

Product of the Month September 2016

Source link

Leave a Comment

Your email address will not be published. Required fields are marked *