我写了一个程序测试多媒体定时器的精读,但测试结果很不理想,只有当精读设置为250ms以上时才显示无误差。
下面是代码和测试结果
#include "stdafx.h"#include <stdio.h>
#include <windows.h>
#include <Mmsystem.h>
#pragma comment(lib,"winmm.lib")  //安装多媒体定时器支持库,也可手动将winmm.lib添加到工程中。     
#include <string>
#include <vector>#define N 10  
using namespace std;
char buffer[128] = {0};
vector <string> g_times;
void CALLBACK fun(UINT uID,UINT uMsg,DWORD dwUser,DWORD dw1,DWORD dw2)
{
sprintf(buffer, "Current time:%lu\n",timeGetTime());
string szTime = buffer;
g_times.push_back(szTime);
}int _tmain(int argc, _TCHAR* argv[])
{
UINT wTimerRes;//=TIMER_ACCURACY; //定义时间间隔
UINT wAccuracy; //定义分辨率
UINT TimerID; //定义定时器句柄
TIMECAPS tc;
cin >> wTimerRes;
if(timeGetDevCaps(&tc,sizeof(TIMECAPS))==TIMERR_NOERROR)
{
wAccuracy=min(max(tc.wPeriodMin,wTimerRes),tc.wPeriodMax); //判断分辨率是否在允许范围
timeBeginPeriod(wAccuracy);  //设置定时器分辨率
} //设置定时器回调事件,回调函数形如fun
if((TimerID=timeSetEvent(wTimerRes,wAccuracy,(LPTIMECALLBACK)fun,0,TIME_PERIODIC))==0)
{
printf("Can't count!\n");
} Sleep(N*wTimerRes);  //等待定时器线程执行N*TIMER_ACCURACY ms timeKillEvent(TimerID);
timeEndPeriod(wAccuracy);
for (vector<string>::iterator ter = g_times.begin(); ter != g_times.end(); ++ter)
{
string sz = *ter;
cout << sz;
}
}结果:
10ms
Current time:4844453
Current time:4844468
Current time:4844468
Current time:4844484
Current time:4844500
Current time:4844500
Current time:4844515
Current time:4844531
Current time:4844531
Current time:4844546
Press any key to continue50ms
Current time:4861328
Current time:4861374
Current time:4861421
Current time:4861468
Current time:4861515
Current time:4861578
Current time:4861624
Current time:4861671
Current time:4861718
Current time:4861765
Press any key to continue100
Current time:4875703
Current time:4875796
Current time:4875906
Current time:4875999
Current time:4876093
Current time:4876203
Current time:4876296
Current time:4876406
Current time:4876499
Current time:4876593
Press any key to continue
200
Current time:4888359
Current time:4888562
Current time:4888765
Current time:4888968
Current time:4889156
Current time:4889359
Current time:4889562
Current time:4889765
Current time:4889968
Current time:4890156
Press any key to continue250
Current time:4903124
Current time:4903374
Current time:4903624
Current time:4903874
Current time:4904124
Current time:4904374
Current time:4904624
Current time:4904874
Current time:4905124
Current time:4905374
Press any key to continue