In three ways, the first uses high-precision performance counters, the second is the use of multimedia timers, and the other is the CPU cycles provided in Windows graphics programming. The first method of measurement is recommended:
Let's look at the first type:
[CPP]View Plaincopy
- #include <windows.h>
- #include <stdio.h>
- void Main ()
- {
- Large_integer litmp;
- Longlong Qt1,qt2;
- double DFT,DFF,DFM;
- //Get clock frequency
- QueryPerformanceFrequency (&LITMP); //Get clock frequency
- dff= (double) litmp. QuadPart;
- //Get initial value
- QueryPerformanceCounter (&LITMP);
- Qt1=litmp. QuadPart;
- //below some time-consuming operations
- Sleep (1);
- //Get termination value
- QueryPerformanceCounter (&LITMP);
- Qt2=litmp. QuadPart;
- //Get the corresponding time value, go to the millisecond unit
- Dfm= (Double) (QT2-QT1);
- DFT=DFM/DFF;
- printf ("spents:%.3f milliseconds \ n", dft*1000.0);
- }
On my machine for Sleep (1) = 0.454ms;sleep (Ten) = 9.719ms;sleep (+) = 99.541ms
Here are two other options for reference:
[CPP]View Plaincopy
- #include <stdio.h>
- #include <Windows.h>
- #include <Mmsystem.h>
- #include "Timer.h"
- #pragma comment (lib, "Winmm.lib")
- int i = 0;
- DWORD start;
- DWORD end;
- #define TIMES (1000)
- void Main ()
- {
- ////////////////////////////////////////////////////////////////////////////////
- //
- //1. Initialize with a high-precision timer
- //
- //high-precision timer initialization
- //NOTE: If you do not execute the following statement initialized to 1ms, the precision of sleep () will be affected
- :: Timebeginperiod (1);
- Sleep (100);
- //Start timing
- Start =:: timeGetTime ();
- For (i=0; i<times; i++)//cumulative test
- {
- Sleep (1);
- }
- //End Timing
- End =:: timeGetTime ();
- printf ("Use a high-precision timer to test sleep (1) Time:%.3f ms\n", (End-start)/((Double) times));
- ////////////////////////////////////////////////////////////////////////////////
- //
- //2. Using the number of CPU cycles to get
- //
- Ktimer timer;
- ///below to get CPU speed (MHZ)
- Timer. Start ();
- Sleep (1000);
- unsigned __int64 cpuspeed = (unsigned) (timer. Stop ()/1000000);
- printf ("CPU speed:%i64d mhz\n", cpuspeed);
- //Start testing
- Timer. Start ();
- Sleep (1);
- //End
- unsigned __int64 time = (unsigned) timer. Stop ();
- printf ("sleep (1) time measured with CPU cycles:%i64dμs\n", time/cpuspeed);
- //
- //After the test is completed, the timing accuracy is recalled
- //
- :: Timeendperiod (1);
- }
The accuracy test of Win32 function sleep