需求
由于程序使用阻塞方式计时,导致程序效率过低,使用定时器来进行计时,保证程序效率
解决
https://docs.microsoft.com/en-us/previous-versions//ms713423(v=vs.85)?redirectedfrom=MSDN
MMRESULT timeSetEvent(
UINT uDelay,
UINT uResolution,
LPTIMECALLBACK lpTimeProc,
DWORD_PTR dwUser,
UINT fuEvent
);
参考微软的文档,进行实现
#include <Windows.h> //需要包含该头文件
#include <stdio.h>
#pragma comment(lib,"Winmm.lib") //For timeSetEvent
//定时器的回调函数
void WINAPI TimerCallback(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
{
*(int*)dwUser=*(int*)dwUser+1;
}
int main(int argc)
{
DWORD_PTR dwUser = NULL;
int time=0;
// 设置定时器
dwUser=&time;
int timerID = timeSetEvent(1000, 1, (LPTIMECALLBACK)TimerCallback, dwUser, TIME_PERIODIC);
if(timerID != NULL)
printf("ok\n");
char ch = '0';
while(ch != 'q')
{
//ch = getchar();
//sleep(1);
printf("%d\n",time);
}
timeKillEvent(timerID); //关闭定时器
return 0;
}
实现功能每秒对计时加一,并且不会阻塞进程,保证效率
参考
https://docs.microsoft.com/en-us/previous-versions//ms713423(v=vs.85)?redirectedfrom=MSDN