Introduction
This article describes how to use C # For a high-precision timer. Sometimes we need a timer with higher accuracy and sleep, but the sleep is not accurate.
So I had to customize it myself.
Background
In general systems, sleep (1) is equivalent to 15.625 ms (1/64 seconds), that is, sleep (15) is the same as sleep.
Microsoft msdn references
Source code
[Structlayout (layoutkind. sequential)] <br/> public struct MSG <br/>{< br/> Public intptr handle; <br/> Public uint MSG; <br/> Public intptr wparam; <br/> Public intptr lparam; <br/> Public uint time; <br/> public system. drawing. point P; <br/>}< br/> public class accuratetimer <br/>{< br/> Public static bool istimebeginperiod = false; </P> <p> const int pm_remove = 0x0001; </P> <p> [dllimport ("kernel32.dll", setlasterror = true)] <br/> static extern bool peekmessage (Out MSG lpmsg, intptr hwnd, uint wmsgfiltermin, <br/> uint wmsgfiltermax, uint wremovemsg ); </P> <p> [dllimport ("kernel32.dll", setlasterror = true)] <br/> static extern bool translatemessage (ref MSG lpmsg ); </P> <p> [dllimport ("kernel32.dll", setlasterror = true)] <br/> static extern bool dispatchmessage (ref MSG lpmsg ); </P> <p> [dllimport ("kernel32.dll", setlasterror = true)] <br/> Public static extern bool queryperformancecounter (ref int64 count ); </P> <p> [dllimport ("kernel32.dll", setlasterror = true)] <br/> Public static extern bool queryperformancefrequency (ref int64 frequency ); </P> <p> Public static int gettimetick () <br/> {<br/> return environment. tickcount; <br/>}</P> <p> Public static void accuratesleep (INT a_i4msec) <br/>{< br/> int64 t_i8frequency = 0; <br/> int64 t_i8starttime = 0; <br/> int64 t_i8endtime = 0; <br/> double t_r8passedmsec = 0; <br/> MSG; <br/> accuratetimer. queryperformancecounter (ref t_i8starttime); <br/> accuratetimer. queryperformancefrequency (ref t_i8frequency); <br/> DO <br/>{< br/> If (accuratetimer. peekmessage (Out MSG, intptr. zero, 0, 0, pm_remove) <br/>{< br/> accuratetimer. translatemessage (ref MSG); <br/> accuratetimer. dispatchmessage (ref MSG); <br/>}< br/> accuratetimer. queryperformancecounter (ref t_i8endtime); <br/> t_r8passedmsec = (double) (t_i8endtime-t_i8starttime)/(double) t_i8frequency) * 1000; <br/>}while (t_r8passedmsec <= a_i4msec); <br/>}< br/>}
Description
Queryperformancefrequency: CPU performance per second (tick)
Queryperformancecounter: You can obtain the number of tick instances running on the CPU.
In this program example, I wrote an accuratesleep function because the sleep precision is only 15.625 milliseconds.
If only the timer is accurate, but the sleep is not accurate, then the accuracy below 15.625 milliseconds cannot be measured.
However, if you only use the while loop to wait, the program will not respond. Therefore, in the loop, you need to process the Windows message to prevent the program from responding.
References