VC++ 下多媒体高精度定时器timeSetEvent

来源:互联网 发布:数据库概论第四版 编辑:程序博客网 时间:2024/05/19 18:14

VC++ 下多媒体高精度定时器timeSetEvent  

 

    用经典API SetTimer恐怕是老生长谈了,但是他的精度不高,不能满足一些要求,容易造成定时器飘移(timer overrun as i
translated)。原因是考虑了系统发出并处理定时器的微小间隔。
    下面介绍一下VC6.0 里面的多媒体定时器,是基于硬件中断的,因此精度高(Linux下的一般中断都是软中断,除非是要求相当苛刻);
常用到的api如下:
1》MMRESULT timeSetEvent( UINT uDelay, UINT uResolution, LPTIMECALLBACK lpTimeProc, DWORD dwUser, UINT fuEvent); 
设置timer事件对象;
uDelay  是定时器间隔;
uResolution 是分辨率,即定时器的精度,为0表示尽可能最大;
lpTimeProc是定时器回调;
dwUser 是回调参数;
fuEvent  是定时器的属性:
      TIME_ONESHOT 表示回调执行一次
TIME_PERIODIC表示回调周期性执行;
该函数返回值为定时器对象id;

2》MMRESULT timeKillEvent( UINT uTimerID );
清除定时器对象;

例子:

// 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(200);
}
return 0;
}
0 0
原创粉丝点击