A Better Timer for a Delphi Programmer

6

The standard VCL TTimer component is a wrapper for the Windows API timer functions SetTimer and KillTimer. TTimer simplifies the processing of the WM_TIMER messages by converting them into OnTimer events. A timer based on WM_TIMER message processing cannot provide a resolution better than 10 milliseconds. And even when the timer interval is set to tens of milliseconds, the actual timer intervals are noticeably higher. The Windows API provides several opportunities to make a better timer – these are multimedia timers, waitable timers and queue timers. I have tried the third alternative (queue timer) as a replacement for the standard VCL TTimer component. The result is TksTimer component added to the ksTools package version 0.46. From the end user point of view the main difference between TTimer and TksTimer is a setting of the timer interval. TksTimer encapsulates the additional functionality of the queue timers and uses 2 properties (namely DueTime and Period) to set the timer interval. The DueTime property sets the interval between the moment the timer is enabled and the moment the timer fires for the first time. The Period property sets the interval between the subsequent timer events. If the Period is set to zero, the timer fires only once.
I have also written TimerTests application to compare the efficiency of TTimer and TksTimer. The difference is outstanding for the intervals of 100 milliseconds or less. I have obtained the following correlation between the set intervals and the average actual timer intervals (in milliseconds) on my computer (Pentium IV, 3.2 GHz, 2Gb RAM, Win XP):

Interval   TTimer  TksTimer
----------------------------
  100        108       100
   50         62        50
   20         31        20
   10         15        11
    5         15         6
    2         15         3
    1         14         2