timeBeginPeriod 高精度定时器 Sleep

1.timeBeginPeriod 与sleep配合使用实现高精度
#include "timeapi.h"
#pragma comment(lib, "winmm")
//
DWORD __stdcall ThreadTest(LPVOID pThreadParam)
{
    CLog mLog;
    int i = 100;
    timeBeginPeriod(1);//1表示1ms精度
    while (i--)
    {
        mLog.WriteLog("%d", i);
        Sleep(1000);
    }
    timeEndPeriod(1);
    return 0;
}

 

测试结果,不使用timeBeginPeriod 的Sleep精度是15ms,使用timeBeginPeriod 的Sleep精度是3ms

sleep本身的误差无法避免,虽然精度设置了1ms但无论sleep(1000)还是sleep(10) 总会有3ms误差

缺点:大幅提高了cpu占用率

 

2.另一个高精度的sleep函数

//休眠指定毫秒数
void MSleep(long lTime)
{
    LARGE_INTEGER litmp;//64位有符号整数
    LONGLONG QPart1, QPart2;
    double dfMinus, dfFreq, dfTim, dfSpec;
    QueryPerformanceFrequency(&litmp);
    dfFreq = (double)litmp.QuadPart;
    QueryPerformanceCounter(&litmp);
    QPart1 = litmp.QuadPart;
    dfSpec = 0.001*lTime;

    do
    {
        QueryPerformanceCounter(&litmp);
        QPart2 = litmp.QuadPart;
        dfMinus = (double)(QPart2 - QPart1);
        dfTim = dfMinus / dfFreq;
    } while (dfTim < dfSpec);
}

//使用时直接调用就可以了
MSleep(1000);//休眠1秒

 

posted @ 2024-02-23 09:46  ckrgd  阅读(304)  评论(0编辑  收藏  举报