Windows平台高精度时钟计数器封装

来源:互联网 发布:linux挂载windows分区 编辑:程序博客网 时间:2024/05/16 12:11

在平时的开发过程中,经常为了测试程序的性能,需要使用高精度的时钟。在Windows平台下,微软提供了QueryPerformanceFrequency()和 QueryPerformanceCounter()两个API函数。


QueryPerformanceFrequency()    MSDN介绍

QueryPerformanceCounter()        MSDN介绍


为了使用方便,我对这两个函数进行了一个简单的封装。经过本人的长期使用,这两个函数在毫秒级相当稳定,效果非常好。下面是封装的代码:

#pragma once#include <windows.h>class CPerformanceClock{public:CPerformanceClock(): m_QPart1(0), m_QPart2(0){QueryPerformanceFrequency(&m_litmp);//获取硬件支持的高精度计数器的频率m_dfFrequency = (double)m_litmp.QuadPart;// 获得计数器的时钟频率}~CPerformanceClock(){}public:// 启动计时void StartClock(){QueryPerformanceCounter(&m_litmp);m_QPart1 = m_litmp.QuadPart;}// 中止计时void StopClock(){QueryPerformanceCounter(&m_litmp);m_QPart2 = m_litmp.QuadPart;}// 获取计时时长,单位毫秒(ms)double GetClockMs(){double dfPartMinus = (double)(m_QPart2 - m_QPart1);// 起始值与中止值的差值double dfCountTime = dfPartMinus / m_dfFrequency;// 对应时长,单位为秒return dfCountTime * 1000;}private:double m_dfFrequency;// 计数器的时钟频率LARGE_INTEGER m_litmp;// 高精度时钟信息 LONGLONG m_QPart1;// 启动时计数器值LONGLONG m_QPart2;// 中止时计数器值};

再给出一个测试该类的程序:

#include <iomanip>#include <iostream>#include "PerformanceClock.h"using namespace std;int main(){CPerformanceClock preClock;// ios::fixed  将符点数按照普通定点格式处理// ios::right  右对齐cout.setf(ios::fixed | ios::right);for (int i = 0; i < 10000; i++){preClock.StartClock();Sleep(1000);preClock.StopClock();double ms = preClock.GetClockMs();// setw控制对齐位置cout << setw(11) << ms << endl;}system("pause");return 0;}

输出结果部分截图,Sleep精度会因机器不同而有所不同:




说明:以上代码在Visual Studio 2013通过测试。

0 0