延时程序

目录

一、前言

二、参考

三、QueryPerformanceCounter()实现

1.例程1

2.例程2

四、GetTickCount()实现


一、前言

近两年的项目中用到的延时程序收集整理。一般在线程中使用,如果使用系统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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值