用于获取程序性能的高精度计时器(C++)
目前在研究图像处理和模式识别,在图像处理过程中需要知道处理的时间,时间精度要求微秒级,所以用到QueryPerformanceFrequency()和QueryPerformanceCounter()这两个函数,据称该精度可达到微秒级。我把它单独做成了一个类,代码如下:
TimerCounter.h
#include <windows.h>
class TimerCounter
{
public:
TimerCounter(void);//构造函数
~TimerCounter(void);//析构函数
private:
LARGE_INTEGER startCount;//记录开始时间
LARGE_INTEGER endCount;//记录结束时间
LARGE_INTEGER freq;//本机CPU时钟频率
public:
double dbTime;//程序运行的时间保存在这里
public:
void Start();//被测程序开始点处开始计时
void Stop();//被测程序结束点处结束计时
};
TimerCounter.cpp
#include "StdAfx.h"
#include "TimerCounter.h"
#include <iostream>
using namespace std;
TimerCounter::TimerCounter(void)
{
QueryPerformanceFrequency(&freq);//获取主机CPU时钟频率
}
TimerCounter::~TimerCounter(void)
{
}
void TimerCounter::Start()
{
QueryPerformanceCounter(&startCount);//开始计时
}
void TimerCounter::Stop()
{
QueryPerformanceCounter(&endCount);//停止计时
dbTime=((double)endCount.QuadPart-(double)startCount.QuadPart)/(double)freq.QuadPart;//获取时间差
}
测试
void main()
{
TimerCounter tc;
tc.Start();
Sleep(100);
tc.Stop();
cout<<"耗时: "<<tc.dbTime * 1000<<"ms"<<endl;
}
输出:
耗时:109.243ms