高精度计时器类

来源:互联网 发布:淘宝快递多少钱 编辑:程序博客网 时间:2024/06/05 07:43

#include <windows.h>
#include <exception>

class HRTimer
{
public:
    HRTimer();
    double getFrequency();
    void startTimer() ;
    double stopTimer();

private:
    LARGE_INTEGER start;
    LARGE_INTEGER stop;
    double frequency;
};

HRTimer::HRTimer() : start(), stop(), frequency()
{
    frequency = getFrequency();
}

double HRTimer::getFrequency()
{
    LARGE_INTEGER proc_freq = {0};
    if (!::QueryPerformanceFrequency(&proc_freq)) throw std::exception(TEXT("QueryPerformanceFrequency() failed"));
    return (1.0) / static_cast<double>(proc_freq.QuadPart);
}

void HRTimer::startTimer()
{
    DWORD_PTR oldmask = ::SetThreadAffinityMask(::GetCurrentThread(), 0);
    ::QueryPerformanceCounter(&start);
    ::SetThreadAffinityMask(::GetCurrentThread(), oldmask);
}

double HRTimer::stopTimer()
{
    DWORD_PTR oldmask = ::SetThreadAffinityMask(::GetCurrentThread(), 0);
    ::QueryPerformanceCounter(&stop);
    ::SetThreadAffinityMask(::GetCurrentThread(), oldmask);
    return ((stop.QuadPart - start.QuadPart) * frequency);
}

int _tmain(int argc, _TCHAR* argv[])
{
    HRTimer cHRTimer;
    cHRTimer.startTimer();
    Sleep(10000);
    double dElapse = cHRTimer.stopTimer();
}

原创粉丝点击