高精度计时器 -- C++/Windows版

在VC++程序里面做计时器可以用CTime,但是这个精度不高,尤其是在时间间隔很短的情况下可能根本没法用。

对于软件测试,可能需要知道精度很高的时间间隔,这个时候最适合用的就是:QueryPerformanceCounter(简称QPC),这是Windows系统提供的API,可信度非常高,QPC可以精确到1微秒(us),所以即使用在很短的时间间隔上也是有价值的。

下面是用C++封装的一段QPC的代码和一个很小的测试用例,当然不用C++封装直接调用QPC也是可以的。

接口规约:

  1. 开始(start)

  2. 结束(end)

  3. 记录用时(getElapsedTime)

所以,封装以后的程序非常简单:开始计时、停止计时、看一下用了多少时间、重新计时,就是这么简单。

//StopWatch.h
#include <Windows.h>
class CStopWatch
{
public:
    CStopWatch();
    void start();
    void stop();
    double getElapsedTime(); //in s
private:
    LARGE_INTEGER m_start;
    LARGE_INTEGER m_stop;
    LARGE_INTEGER m_frequency;
};

//StopWatch.cpp
CStopWatch::CStopWatch()
{
    m_start.QuadPart = 0;
    m_stop.QuadPart = 0;
    QueryPerformanceFrequency(&m_frequency);
}

void CStopWatch::start()
{
    QueryPerformanceCounter(&m_start);
}

void CStopWatch::stop()
{
    QueryPerformanceCounter(&m_stop);
}

double CStopWatch::getElapsedTime()
{
    LARGE_INTEGER time;
    time.QuadPart = m_stop.QuadPart - m_start.QuadPart;
    return (double)time.QuadPart / (double)m_frequency.QuadPart;
}

//test
#include <stdio.h>
void swap(int & a, int & b)
{
    int t = a;
    a = b;
    b = t;
}
//compile : cl StopWatch.cc
int main()
{
    CStopWatch timer;
    timer.start();
    //...
    int a=1, b=2;
    for (unsigned int i = 0; i < 100000000; ++i)
    {
        swap(a, b);
        swap(a, b);
    }
    timer.stop();
    double d = timer.getElapsedTime();
    printf("%fs\n", d);      //1.166879s
}

 

参考资料:

1. [MSDN] Acquiring high-resolution time stamps

2. [MSDN] QueryPerformanceCounter function

posted @ 2017-05-22 11:26  探索者软件  阅读(3742)  评论(0编辑  收藏  举报