精確擷取時間
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
#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
//MyTimer.cpp
#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;}