QueryPerformanceFrequency用法
精確獲取時間:
QueryPerformanceFrequency() - 基本介紹
類型:Win32API
原型:BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency);
作用:返回硬件支持的高精度計數(shù)器的頻率。
返回值:非零,硬件支持高精度計數(shù)器;零,硬件不支持,讀取失敗。
QueryPerformanceFrequency() - 技術(shù)特點
供WIN9X使用的高精度定時器:QueryPerformanceFrequency()和QueryPerformanceCounter(),要求計算機從硬件上支持高精度定時器。需包含windows.h頭文件。
函數(shù)的原形是:
BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency);
BOOL QueryPerformanceCounter (LARGE_INTEGER *lpCount);
數(shù)據(jù)類型LARGEINTEGER既可以是一個作為8字節(jié)長的整數(shù),也可以是作為兩個4字節(jié)長的整數(shù)的聯(lián)合結(jié)構(gòu),其具體用法根據(jù)編譯器是否支持64位而定。該類型的定義如下:
typeef union _ LARGE_INTEGER
{
struct
{
DWORD LowPart;
LONG HighPart;
};
LONGLONG QuadPart;
} LARGE_INTEGER;
在定時前應該先調(diào)用QueryPerformanceFrequency()函數(shù)獲得機器內(nèi)部計時器的時鐘頻率。接著在需要嚴格計時的事件發(fā)生前和發(fā)生之后分別調(diào)用QueryPerformanceCounter(),利用兩次獲得的計數(shù)之差和時鐘頻率,就可以計算出事件經(jīng)歷的精確時間。
測試Sleep的精確時間:
#include
#include
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");
}
再給出我寫的一個Fibonacci的例子:
#include
#include
#include
#include
#include
using namespace std;
unsigned long Fib1(unsigned long n)
{
return (n == 1 || n == 2) ? 1 : Fib1(n - 1) + Fib1(n - 2);
}
unsigned long Fib2(unsigned long n)
{
if (n == 1 || n == 2)
{
return 1;
}
unsigned long m1 = 1, m2 = 1;
for (unsigned long i = 3; i <= n; i++)
{
m2 = m1 + m2;
m1 = m2 - m1;
}
return m2;
}
int main()
{
LARGE_INTEGER nFreq;
LARGE_INTEGER nBeginTime;
LARGE_INTEGER nEndTime;
double time1 = 0, time2 = 0;
unsigned long result1 = 0;
unsigned long result2 = 0;
unsigned long fib_num = 45;
cout.precision(10);
cout.setf(cout.showpoint); //設置為始終輸出小數(shù)點后的數(shù)字,就是說 a = 3,它也輸出 3.00000 這
QueryPerformanceFrequency(&nFreq);
QueryPerformanceCounter(&nBeginTime);
result1 = Fib1(fib_num);
QueryPerformanceCounter(&nEndTime);
time1=(double)(nEndTime.QuadPart-nBeginTime.QuadPart)/(double)nFreq.QuadPart;
cout<<"Fib1: "<< fixed<
本文題目:C++統(tǒng)計精確時間
分享鏈接:http://weahome.cn/article/jocgsd.html