7 Types of Timers in Windows (VC timer types and occupancy resources comparison)

Source: Internet
Author: User

VC provides a lot of functions about time operations, using their control program can accurately complete timing and timing operations. This article describes in detail the seven ways in which the VC is based on the exact timing of windows, as shown in:

Figure an image description

  Way One: The WM_TIMER message map in VC can make simple time control. First call the function SetTimer () to set the timing interval, such as SetTimer (0,200,null), which is the time interval for setting 200ms. The timer response function OnTimer () is added to the application, and a response processing statement in the function is used to complete the operation to arrive at the timed time. This timing method is very simple, can achieve a certain timing function, but its timing function as the sleep () function, the same as the delay function, the accuracy is very low, the minimum timing accuracy of only 30ms,cpu occupied low, and the timer message in the multitasking operating system priority is very low, can not be timely response, often can not meet the real-time control environment applications. Can only be used to achieve such as the dynamic display of bitmaps, such as the timing of the accuracy of the situation is not high. such as the Timer1 in the example project.
  Way Two: The VC uses the Sleep () function to implement the delay, which is in MS, such as delay of 2 seconds, with Sleep (2000). The accuracy is very low, the minimum timing accuracy is only 30ms, with the sleep function disadvantage lies in the delay period can not process other messages , if the time is too long, as if the crash, CPU occupancy rate is very high, can only be used in the request is not high latency program. such as the Timer2 in the example project.
  method Three: use the COleDateTime class and the COleDateTimeSpan class to combine the Windows message processing process to achieve the second-level delay. such as Timer3 and Timer3_1 in the example project. The following is a delay code that implements 2 seconds:

      COleDateTime      start_time = Coledatetime::getcurrenttime ();      COleDateTimeSpan  end_time= coledatetime::getcurrenttime ()-start_time;      while (End_time. Gettotalseconds () < 2)//Implementation Delay 2 sec     {               msg   msg;              GetMessage (&msg,null,0,0);              TranslateMessage (&msg);               DispatchMessage (&msg);                           The above four lines are implemented during the delay or timing can process other messages,//Although this can reduce the CPU share,             //But reduce the delay or timing accuracy, can be removed in practical applications.             end_time = Coledatetime::getcurrenttime ()-start_time;      } This way we can also handle other messages when the delay is over.      
  mode four:In the case of high precision requirements, VC can take advantage of the GetTickCount () function, the return value of the function isA DWORD type that represents the interval of time that is experienced after a computer is started in Ms. The accuracy is higher than the WM_TIMER message map,Short timing of its timing error is 15ms, in the longer timing of its timing error is low, if the timing is too long, as if the crash, CPU occupancy rate is very high, can only be used in the request is not high delay program. such as Timer4 and Timer4_1 in the example project. The following code enables precise timing of 50ms:
       DWORD Dwstart = GetTickCount ();       DWORD dwend   = Dwstart;       Do       {          dwend = GetTickCount ()-dwstart;       } while (Dwend <50);
To enable the GetTickCount () function to process other messages during delay or timing, you can change the code to:
       DWORD Dwstart = GetTickCount ();       DWORD dwend   = Dwstart;       Do       {              msg   msg;              GetMessage (&msg,null,0,0);              TranslateMessage (&msg);               DispatchMessage (&msg);              Dwend = GetTickCount ()-dwstart;       } while (Dwend <50);
Although this can reduce the CPU's share, and during the delay or timing can also handle other messages, but reduce the delay or timing accuracy.
   Mode five: A multimedia timer function dwordtimegettime (void) similar to the GetTickCount () function, which is timed fineIs the MS level, which returns the number of milliseconds that have elapsed since Windows started. Microsoft Inc. provides the bottom of the precise timer in its multimedia windowsLayer API, the multimedia timer can be used to accurately read the current time of the system, and can be completed within a very precise time intervalA call to an event, function, or procedure. The difference is that the DWORD timegettime (void) function must be called before the Winmm.libAnd Mmsystem.h are added to the project, otherwise the prompt for the DWORD timegettime (void) function is undefined at compile time. Because of the use of theFunctions are timed controlled by means of queries, so a timed loop should be established to control the timing events. such as Timer5 and Timer5_1 in the example project.
   Way Six:Using the multimedia timer timesetevent () function, the function has a timing accuracy of MS class. The function can be used to implement periodic function calls. such as Timer6 and Timer6_1 in the example project. The prototype of the function is as follows:
       Mmresult timesetevent (UINT udelay,                                uint uresolution,                                lptimecallback lptimeproc,                                WORD dwuser,                                UINT Fuevent)
This function sets a timed callback event, which can be a one-time event or a recurring event. Once the event is activated, the specified callback function is invoked.Returns the identifier code of the event after success, otherwise returns NULL. The parameters of the function are described as follows:
       Udelay: Specifies the period of the event in milliseconds.       uresolution: Specify the precision of the delay in milliseconds, the smaller the value the higher the timer event resolution. The default value is 1ms.       Lptimeproc: Point to a callback function.       Dwuser: Store user-provided callback data.       fuevent: Specifies the Timer event type:       Time_oneshot:udelay milliseconds after only one event       Time_periodic: Every udelay millisecond generates events periodically.      
For specific applications, you can define tasks that need to be performed periodically by calling the timeSetEvent () function in the Lptimeproc callback function(e.g., timed sampling, control, etc.) to complete the event that is required to be processed. It is important to note that the task processing time cannot be greater than the period interval. In addition, after the timer has been used,You should call Timekillevent () to release it in a timely manner.
   Way Seven:For more accurate timing operations, you should use the QueryperformancefrequencY () andThe QueryPerformanceCounter () function. These two functions are the exact time functions provided by the VC for use by WINDOWS95 and its subsequent versions, and require the computer to support precise timers from hardware. such as Timer7, Timer7_1, Timer7_2, Timer7_3 in the example project.
QueryperformancefrequencThe Y () function and the QueryPerformanceCounter () function are prototyped as follows:
       BOOL  queryperformancefrequency (large_integer *lpfrequency);       BOOL  QueryPerformanceCounter (Large_integer *lpcount);
The data type Arge_integer can be either a 8-byte integer or a combined structure of two 4-byte integers,Its specific usage depends on whether the compiler supports 64-bit. This type is defined as follows:
       typedef Union _LARGE_INTEGER       {           struct           {              DWORD lowpart;//4-byte integer number              LONG  highpart;//4-byte integer           };           Longlong QuadPart;//8-byte integer number                   }large_integer;
Call Queryperformancefrequenc before timingThe Y () function obtains the clock frequency of the internal timer of the machine,The QueryPerformanceCounter () function is then called before and after the event that requires strict timing, using the two-time count difference and clock frequency to calculate the eventThe exact time of the calendar. The following code implements the exact timing of 1ms:
       Large_integer litmp;        Longlong Qpart1,qpart2;       Double Dfminus, Dffreq, Dftim;        Queryperformancefrequency (&litmp);       Dffreq = (double) litmp. quadpart;//gets the clock frequency of the counter       QueryPerformanceCounter (&litmp);       QPart1 = litmp. quadpart;//get the initial value do       {          queryperformancecounter (&litmp);          QPart2 = litmp. quadpart;//Get abort value          Dfminus = (double) (QPART2-QPART1);          Dftim = dfminus/dffreq;//to obtain the corresponding time value, in seconds       }while (dftim<0.001);
The timing error does not exceed 1 microseconds, and the accuracy is related to machine configuration such as CPU. The following program is used to test the exact duration of the function sleep (100):
       Large_integer litmp;        Longlong Qpart1,qpart2;       Double Dfminus, Dffreq, Dftim;        Queryperformancefrequency (&litmp);       Dffreq = (double) litmp. quadpart;//gets the clock frequency of the counter       QueryPerformanceCounter (&litmp);       QPart1 = litmp. quadpart;//gets the initial value of       Sleep (+);       QueryPerformanceCounter (&litmp);       QPart2 = litmp. quadpart;//Get abort value       Dfminus = (double) (QPART2-QPART1);       Dftim = dfminus/dffreq;//Gets the corresponding time value in seconds     
Due to the error of the sleep () function itself, the results of each execution of the above program will have a slight error. The following code implements a precise timing of 1 microseconds:
       Large_integer litmp;        Longlong Qpart1,qpart2;       Double Dfminus, Dffreq, Dftim;        Queryperformancefrequency (&litmp);       Dffreq = (double) litmp. quadpart;//gets the clock frequency of the counter       QueryPerformanceCounter (&litmp);       QPart1 = litmp. quadpart;//get the initial value do       {          queryperformancecounter (&litmp);          QPart2 = litmp. quadpart;//Get abort value          Dfminus = (double) (QPART2-QPART1);          Dftim = dfminus/dffreq;//to obtain the corresponding time value, in seconds       }while (dftim<0.000001);
The timing error generally does not exceed 0.5 microseconds, the accuracy of the CPU and other machine configuration.

7 Types of Timers in Windows (VC timer types and occupancy resources comparison)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.