用于获取程序性能的高精度计时器(C++)

目前在研究图像处理和模式识别,在图像处理过程中需要知道处理的时间,时间精度要求微秒级,所以用到QueryPerformanceFrequency()和QueryPerformanceCounter()这两个函数,据称该精度可达到微秒级。我把它单独做成了一个类,代码如下:

TimerCounter.h

 1 #include <windows.h>
2
3
4 class TimerCounter
5 {
6 public:
7   TimerCounter(void);//构造函数
8   ~TimerCounter(void);//析构函数
9
10 private:
11   LARGE_INTEGER startCount;//记录开始时间
12
13   LARGE_INTEGER endCount;//记录结束时间
14
15   LARGE_INTEGER freq;//本机CPU时钟频率
16
17 public:
18   double dbTime;//程序运行的时间保存在这里
19
20 public:
21   void Start();//被测程序开始点处开始计时
22   void Stop();//被测程序结束点处结束计时
23 };

TimerCounter.cpp

 1 #include "StdAfx.h"
2 #include "TimerCounter.h"
3 #include <iostream>
4
5
6 using namespace std;
7 TimerCounter::TimerCounter(void)
8 {
9 QueryPerformanceFrequency(&freq);//获取主机CPU时钟频率
10 }
11
12 TimerCounter::~TimerCounter(void)
13 {
14 }
15
16 void TimerCounter::Start()
17 {
18 QueryPerformanceCounter(&startCount);//开始计时
19 }
20
21 void TimerCounter::Stop()
22 {
23 QueryPerformanceCounter(&endCount);//停止计时
24
25 dbTime=((double)endCount.QuadPart-(double)startCount.QuadPart)/(double)freq.QuadPart;//获取时间差
26
27 }

测试:

 1  void main()
2 {
3 TimerCounter tc;
4
5 tc.Start();
6 Sleep(100);
7 tc.Stop();
8
9 cout<<"耗时: "<<tc.dbTime * 1000<<"ms"<<endl;
10 }

结果:

1 耗时:109.243ms

原文链接: https://www.cnblogs.com/davy2495/archive/2012/02/12/2348284.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    用于获取程序性能的高精度计时器(C++)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/41456

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午6:19
下一篇 2023年2月8日 下午6:19

相关推荐