C++记录精确时间-QueryPerformanceFrequency()

xiaoxiao2021-02-28  118

精确获取时间

QueryPerformanceFrequency() - 基本介绍

类型:Win32API

原型:BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency);

作用:返回硬件支持的高精度计数器的频率。

返回值:非零,硬件支持高精度计数器;零,硬件不支持,读取失败。

QueryPerformanceFrequency() - 技术特点

供WIN9X使用的高精度定时器:QueryPerformanceFrequency()和QueryPerformanceCounter(),要求计算机从硬件上支持高精度定时器。需包含windows.h头文件。

函数的原形是:

BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency);

BOOL QueryPerformanceCounter (LARGE_INTEGER *lpCount);

数据类型LARGEINTEGER既可以是一个作为8字节长的整数,也可以是作为两个4字节长的整数的联合结构,其具体用法根据编译器是否支持64位而定。该类型的定义如下:

typeef union _ LARGE_INTEGER

{

struct

{

DWORD LowPart;

LONG HighPart;

};

LONGLONG QuadPart;

} LARGE_INTEGER;

在定时前应该先调用QueryPerformanceFrequency()函数获得机器内部计时器的时钟频率。接着在需要严格计时的事件发生前和发生之后分别调用QueryPerformanceCounter(),利用两次获得的计数之差和时钟频率,就可以计算出事件经历的精确时间。

测试Sleep的精确时间:

#include <stdio.h>

#include <windows.h>

void main()

{

     LARGE_INTEGER nFreq;

     LARGE_INTEGER nBeginTime;

     LARGE_INTEGER nEndTime;

     double time;

 

     QueryPerformanceFrequency(&nFreq);

     QueryPerformanceCounter(&nBeginTime); 

 

     Sleep(1000);

 

     QueryPerformanceCounter(&nEndTime);

     time=(double)(nEndTime.QuadPart-nBeginTime.QuadPart)/(double)nFreq.QuadPart;

 

     printf("%f\n",time);

     Sleep(1000);

system("Pause");

}

结果为

0.999982

1.000088

1.000200

单位为妙,乘1000000即为微秒

------------------------------------------------------------------------

一个MyTimer类及使用

//MyTimer.h

[cpp]  view plain  copy  print ? <span style="font-family:SimSun;font-size:18px;">#ifndef MYTIMER_H   #define MYTIMER_H   #include <windows.h>      class MyTimer   {   private:       LONGLONG _freq;       LARGE_INTEGER _begin;       LARGE_INTEGER _end;      public:       long costTime;            // 花费的时间(精确到微秒)      public:       MyTimer()       {           LARGE_INTEGER tmp;           QueryPerformanceFrequency(&tmp);           _freq=tmp.QuadPart;           costTime=0;       }          void Start()            // 开始计时       {           QueryPerformanceCounter(&_begin);       }          void End()                // 结束计时       {           QueryPerformanceCounter(&_end);           costTime=(long)((_end.QuadPart - _begin.QuadPart)*1000000/_freq);       }          void Reset()            // 计时清0       {           costTime = 0;       }   };   #endif   </span>  

//MyTimer.cpp

[cpp]  view plain  copy  print ? <span style="font-family:SimSun;font-size:18px;">#include "stdafx.h"   #include "MyTimer.h"   #include <iostream>   using namespace std;      int _tmain(int argc, _TCHAR* argv[])   {       int i=10000;       MyTimer mt;       mt.Start();       while((i--)>0);       mt.End();       cout<<"所用时间为 "<<mt.costTime<<"us"<<endl;       return 0;   }   </span>  
转载请注明原文地址: https://www.6miu.com/read-45255.html

最新回复(0)