Author: Jonas Bilinkevicius
How to create a high resolution timer
Answer:
Windows is not a real time operating system so it is not really able to reliably
achieve high accuracy timing without using a device driver. The best I have been
able to get is a few nanoseconds using QueryPerformanceCounter. This is the
procedure I use:
1 var2 WaitCal: Int64;
3 4 procedure Wait(ns: Integer);
5 var6 Counter, Freq, WaitUntil: Int64;
7 begin8 if QueryPerformanceCounter(Counter) then9 begin10 QueryPerformanceFrequency(Freq);
11 WaitUntil := Counter + WaitCal + (ns * (Freq div 1000000));
12 while Counter < WaitUntil do13 QueryPerformanceCounter(Counter);
14 end15 else16 Sleep(ns div 1000);
17 end;
18 19 //To get improved accuracy do this a little while before using Wait()20 21 var22 Start, Finish: Int64;
23 24 Application.ProcessMessages;
25 Sleep(10);
26 QueryPerformanceCounter(Start);
27 Wait(0);
28 QueryPerformanceCounter(Finish);
29 WaitCal := Start - Finish;
30 31 {A trick I have found to increase the reliability of this on my computer is to call 32 Wait like this:}33 34 Application.ProcessMessages;
35 Sleep(0);
36 DoSomething;
37 Wait(10);
38 DoSomethingElse;