Use of Timers

Source: Internet
Author: User
Tags sleep function

The timer (timer) in the Windows program design many places can use, his main purpose is according to the program set interval time, intermittently produces the WM_TIMER message, sends to the specified window, in the window carries on the processing to the WM_TIMER message, completes the designated task!

Explanation of ① and timer functions:

Timer start function: SetTimer

UINT SetTimer (UINT nidevent,//Timer identification              UINT Nelapse,  //timer interval void (CALLBACK export* lpfntimer) (H WND,//timer response function, null default OnTimer function; uint, uint, DWORD);

Timer response function: OnTimer

afx_msg void OnTimer (UINT nidevent), void Cmfctestdlg::ontimer (Uint_ptr nidevent) {  //todo:add your message Handl ER code here and/or Calldefault Cdialog::ontimer (nidevent);}

Timer End Function: KillTimer

KillTimer (time_id);//time_id the ID of the timer, destroying the time-only authentication.

Use of ② and timers:

Define Timer constants:

#define ID_TIME1  1#define id_time2 2

To set the start timer:

SetTimer (id_time1,1000,0); SetTimer (id_time2,500,0);

Timer function Response:

OID Cmainframe::ontimer (UINT nidevent) {    //todo:add your message handler code here and/or call default    switch (n idevent) {case    id_time1:        {               AfxMessageBox ("Timer 1!");            break;        } Case Id_time2:        {               AfxMessageBox ("Timer 2!");            break;        }    Default:        ;}

Destroy timer:

KillTimer (ID_TIME1); KillTimer (id_time2);

Precise Windows-based timing in VC   

In the industrial production control system, there are many operations that need to be completed regularly, such as timing display current time, timed to refresh the screen progress bar, the host computer timed down to send commands and data transmission. Especially in the real-time control system and data acquisition system with high control performance, the precise timing operation is more necessary.
As we all know, Windows is a message-based system, and any event execution is done by sending and receiving messages. This poses problems such as when a computer's CPU is occupied by a process, or if the system resources are strained, messages sent to the message queue are temporarily suspended and not processed in real time. Therefore, it is not easy to raise a timed-critical event through Windows messages. Also, because access to the computer's underlying hardware has been encapsulated in Windows, it can be difficult to achieve precise timing by directly leveraging access hardware. Therefore, in the actual application, should be aimed at the specific timing accuracy requirements, to adopt a suitable timing method.
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:

Mode one: VC in the WM_TIMER message map can be a 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, like the delay function, the accuracy is very low, the minimum timing accuracy of only 30ms,cpu occupy low, and the timer message in the multi-task 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. Mode two: VC using the Sleep () function to achieve the delay, it is the unit of 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 accuracy requirements, VC can take advantage of the GetTickCount () function, the return value of the function is a DWORD type, indicating the time interval after the computer starts in Ms. The accuracy is higher than the WM_TIMER message map, its timing error is 15ms in the shorter timing, its timing error is low in the longer timing, if the timing time 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 similar to the GetTickCount () function, DWORD timegettime (void), the function has a timing accuracy of MS, and returns the number of milliseconds that have elapsed since Windows started. Microsoft provides the underlying API for precise timers in its multimedia windows, using a multimedia timer to accurately read the current time of the system and to complete the invocation of an event, function, or procedure in a very precise time interval. The difference is that Winmm.lib and Mmsystem.h must be added to the project before the DWORD timeGetTime (void) function is called, otherwise the DWORD timegettime (void) function is not defined at compile time. Due to the use of this function is the method of timing control through the query, so, should establish a timing loop to control the timing events.   such as Timer5 and Timer5_1 in the example project. Mode VI: 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, the identifier code of the event is returned after success, otherwise NULL is returned. 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 complete the desired event by calling the timeSetEvent () function and defining the tasks that need to be executed periodically in the Lptimeproc callback function (e.g., timed sampling, control, etc.). It is important to note that the task processing time cannot be greater than the period interval.   In addition, after the timer is used, the timekillevent () should be called in time to release it. Method Seven: For more precise timing operations, you should use the QueryPerformanceFrequency () and QueryPerformanceCounter () functions. These are the exact time functions provided by the VC for use by Windows 95 and subsequent versions only, and require the computer to support precise timers from the hardware. such as Timer7, Timer7_1, Timer7_2, Timer7_3 in the example project. The QueryPerformanceFrequency () 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 union structure of two 4-byte-long integers, depending 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;

Before timing, call the QueryPerformanceFrequency () function to get the clock frequency of the internal timer of the machine, and then call the QueryPerformanceCounter () function before and after the event that requires strict timing. The exact time of the event is calculated using the count difference and clock frequency obtained two times. 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. Finish

Reprint: http://www.cnblogs.com/szjoin/archive/2004/11/26/69346.html

Use of Timers

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.