Multimedia High precision timer timeSetEvent with VC + +
With the classic API SetTimer I'm afraid it is the old growth talk, but his precision is not high, can not meet some requirements, easy to cause the timer drift (timer overrun as I translated). The reason is to consider the system to emit and handle the small interval of timers. Here is a description of the multimedia timer inside the VC6.0, which is based on hardware interrupts, so high precision (the general interruption under Linux is soft interrupt, unless it is very demanding); The common APIs are as follows:1 "Mmresult timesetevent" (UINTUdelay, UINTUresolution, LptimecallbackLptimeproc, DWORDDwuser, UINTFuevent);
Set Timer event object; Udelay is the timer interval; uresolution is the resolution, that is, the precision of the timer, which is 0 as maximum; Lptimeproc is the timer callback; Fuevent is the timer's property: T Ime_oneshot indicates that the callback executes once time_periodic indicates that the callback is executed periodically, and the function returns a value of the Timer object ID;
2 "Mmresult timekillevent" (UINTUtimerid); clears the timer object;
Example:
TimeSetEvent.cpp:Defines the entry point for the console application. //
#include "stdafx.h" #include "windows.h" #include "mmsystem.h" #include "iostream" #pragma comment (lib, "Winmm.lib") using namespace Std;
Mmresult Timerid; volatile int i=0; void CALLBACK Timeproc (UINT UID, UINT umsg, DWORD Dwuser, DWORD Dw1, DWORD dw2) {if (Uid==timerid) {cout<<++i<<endl; if (i==10) {timekillevent (Timerid); } } }
int main (int argc, char* argv[]) {//printf ("Hello world!\n"); Timerid=timesetevent (1000,0,timeproc,null,time_periodic); if (timerid==null) {cout<< "timeSetEvent error" <<endl;} for (int j=0;j<5000;j++) {sleep;} Retu RN 0; }