目录
一、前言
近两年的项目中用到的延时程序收集整理。一般在线程中使用,如果使用系统api函数Sleep(),将会导致线程休眠挂起,如果频繁调用将导致线程运行挂起和恢复重复执行,占用系统CPU的资源,相对来说开销会比较大。比较几种延时方式,QueryPerformanceCounter()精度最高,GetTickCount()次之,sleep()再次之,time()最次。精度高并不代表性能好,相反,多次重复执行相同的次数消耗的时间越多,这个可以查看参考博客1。
二、参考
1.《windows平台时间函数性能比较QueryPerformanceCounter,GetTickCount,ftime,time,GetLocalTime,GetSystemTimeAsFileTime》[代码如诗https://www.cnblogs.com/kex1n/p/3297607.html]
三、QueryPerformanceCounter()实现
1.例程1
void Timekeeper(UINT Milliseconds)
{
//计时处理
LONGLONG nBeginCount = 0, nCount = 0, nEndCount = 0;
LARGE_INTEGER lFreq; //存储计数的联合体
double time = 0; //计时时间
double fre = 0; //服务器CPU时钟频率
QueryPerformanceFrequency(&lFreq); //获取服务器CPU频率
fre = (double)(lFreq.QuadPart)/1000; //单位Hz/1000,即 次/毫秒
do
{
QueryPerformanceCounter((LARGE_INTEGER*)&nCount);
if (nBeginCount == 0)
{
nBeginCount = nCount;
}
else
{
nEndCount = nCount;
time = (nEndCount - nBeginCount) / fre;
}
} while (time < Milliseconds);//如果延时大于超时秒数,退出
return;
}
2.例程2
bool TimerDog(long long& nBeginCount, UINT Milliseconds)
{
//计时处理
long long nCount = 0, nEndCount = 0;
LARGE_INTEGER lFreq; //存储计数的联合体
double time = 0; //计时时间
double fre = 0; //服务器CPU时钟频率
QueryPerformanceFrequency(&lFreq); //获取服务器CPU频率
fre = (double)(lFreq.QuadPart) / 1000; //单位Hz/1000,即 次/毫秒
QueryPerformanceCounter((LARGE_INTEGER*)&nCount);
if (nBeginCount == 0)
{
nBeginCount = nCount;
}
else
{
nEndCount = nCount;
time = (nEndCount - nBeginCount) / fre;
}
if (time < Milliseconds)//如果延时大于超时秒数,退出
{
return false;
}
return true;
}
四、GetTickCount()实现
// 毫秒延时程序
int DelayTimer(UINT MilliSecond)
{
DWORD dwStart = GetTickCount();
DWORD dwEnd = dwStart;
do
{
MSG msg;
GetMessage(&msg, NULL, 0, 0);
TranslateMessage(&msg);
DispatchMessage(&msg);
dwEnd = GetTickCount() - dwStart;
} while (dwEnd < MilliSecond);
return 0;
}