软件开发中,经常会涉及到计时的操作,下面总结下实现计时器的几种方法。
方法一:
使用SetTimer()和OnTimer()实现计时操作。
SetTimer设置OnTimer的调用属性
SetTimer(100,100,NULL);OnTimer根据SetTimer的设置定时刷新数据
void CDemoView::OnTimer(UINT nIDEvent) { // TODO: Add your message handler code here and/or call default CView::OnTimer(nIDEvent); }
方法二:
精确的时间计时
QueryPerformanceFrequency查询定时器的执行频率
QueryPerformanceCounter查询定时器的计数值
//初始化值 DWORD dwMsecond = 0; LARGE_INTEGER cpuHz, startCnt, targetCnt; cpuHz.QuadPart = 0; startCnt.QuadPart = 0; targetCnt.QuadPart = 0; QueryPerformanceFrequency(&cpuHz); QueryPerformanceCounter(&startCnt); //开始计时 QueryPerformanceCounter(&targetCnt); dwMsecond = (DWORD)((targetCnt.QuadPart - startCnt.QuadPart)/cpuHz.QuadPart*1000); if (dwMsecond > dwTimeout) { }
方法三:
GetTickCount是计算机编程中的函数,指返回(retrieve)从操作系统启动所经过(elapsed)的毫秒数,它的返回值是DWORD。
MSG msg; DWORD dwTimeStarted; dwTimeStarted = ::GetTickCount(); //等待1000ms while(::GetTickCount() - dwTimeStarted < 1000) { if(PeekMessage(&msg,0,0,0,PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } } //超过10s退出 if(::GetTickCount() - dwTimeStarted > 10*1000) { if(PeekMessage(&msg,0,0,0,PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } return ; }
原文地址:http://blog.csdn.net/bingdianlanxin/article/details/43613325