图一、实现微秒级的精确定时器 |
MMRESULT timeSetEvent(UINT uDelay,UINT uResolution,LPTIMECALLBACK lpTimeProc, DWORD dwUser,UINT fuEvent); |
# define ONE_MILLI_SECOND 1 //定义1ms和2s时钟间隔,以ms为单位 ; # define TWO_SECOND 2000 # define TIMER_ACCURACY 1 //定义时钟分辨率,以ms为单位 UINT wTimerRes_1ms,wTimerRes_2s; //定义时间间隔 UINT wAccuracy; //定义分辨率 UINT TimerID_1ms,TimerID_2s; //定义定时器句柄 /////////////////////////////// CCureApp::CCureApp():fout("cure.out", ios::out) //打开输出文件"cure.out"; { // 给时间间隔变量赋值 wTimerRes_1ms = ONE_MILLI_SECOND; wTimerRes_2s = TWO_SECOND; TIMECAPS tc; //利用函数timeGetDevCaps取出系统分辨率的取值范围,如果无错则继续; if(timeGetDevCaps(&tc,sizeof(TIMECAPS))==TIMERR_NOERROR) { wAccuracy=min(max(tc.wPeriodMin, //分辨率的值不能超出系统的取值范围 TIMER_ACCURACY),tc.wPeriodMax); //调用timeBeginPeriod函数设置定时器的分辨率 timeBeginPeriod(wAccuracy); //设置定时器 InitializeTimer(); } } CCureApp:: ~CCureApp() { fout <<"结束时钟"<< endl; //结束时钟 timeKillEvent(TimerID_1ms); // 删除两个定时器 timeKillEvent(TimerID_2s); // 删除设置的分辨率 timeEndPeriod(wAccuracy); } void CCureApp::InitializeTimer() { StartOneMilliSecondTimer(); StartTwoSecondTimer(); } //1ms定时器的回调函数,类似于中断处理程序,一定要声明为全局PASCAL函数, //否则编译会有问题 void PASCAL OneMilliSecondProc(UINT wTimerID, UINT msg,DWORD dwUser, DWORD dwl,DWORD dw2) { // 定义计数器 static int ms = 0; CCureApp *app = (CCureApp *)dwUser; // 取得系统时间,以ms为单位 DWORD osBinaryTime = GetTickCount(); //输出计数器值和当前系统时间 app->fout<<++ms<<":1ms:" } // 加装1ms定时器 void CCureApp::StartOneMilliSecondTimer() { if((TimerID_1ms = timeSetEvent(wTimerRes_1ms, wAccuracy, (LPTIMECALBACK) OneMil liSecondProc, // 回调函数; (DWORD)this, // 用户传送到回调函数的数据; TIME_PERIODIC)) == 0)//周期调用定时处理函数; { AfxMessageBox("不能进行定时!", MB_OK | MB_ICONASTERISK); } else fout << "16ms 计 时:" << endl; //不等于0表明加装成功,返回此定时器的句柄; } |