C # timer,
C # Timer
In C #, there are 4 commonly used Timers:
- System. Timers. Timer and System. Windows. Forms. Timer have a minimum recognition of 1/18 s.
- TimeGetTime, which has a minimum recognition capability of 5 ms.
- System. Environment. TickCount, which is recognized at least in millimeters.
- QueryPerformanceCounter, which is identified as 1 ms at the lowest.
// Take QueryPerformanceCounter as an example: public class Program {// reference QueryPerformanceCounter () in Win32 API () method // This method calls to query the actual value of the high-precision counter at any time [DllImport ("Kernel32.dll")] private static extern bool QueryPerformanceCounter (out long lpPerformanceCount ); // reference the QueryPerformanceFrequency () method in Win32 API // This method returns the Count value of the high-precision counter per second [DllImport ("Kernel32.dll")] private static extern bool QueryPerformanceFrequency (out long lpFrequency ); public static void Main (string [] args) {long startTime, endTime; long freq; if (QueryPerformanceFrequency (out freq) = false) {// high-performance timer throw new Win32Exception ();} Thread. sleep (0); // Let the waiting thread work. In this example, it is a single thread, and QueryPerformanceCounter (out startTime) can be omitted; // record the start time, precision: 1 ms for (int I = 0; I <10000; I ++) {for (int j = 0; j <10000; j ++) {int temp = 0 ;}} QueryPerformanceCounter (out endTime); // record end time, accurate to 1 ms Console. writeLine (double) (endTime-startTime) * 1000/freq + "ms"); Console. readKey () ;}// Result: // 412.58911914026 ms // The Result varies depending on the performance of your PC.