您好,登錄后才能下訂單哦!
QueryPerformanceFrequency用法 精確獲取時間: 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字節(jié)長的整數,也可以是作為兩個4字節(jié)長的整數的聯合結構,其具體用法根據編譯器是否支持64位而定。該類型的定義如下: typeef union _ LARGE_INTEGER { struct { DWORD LowPart; LONG HighPart; }; LONGLONG QuadPart; } LARGE_INTEGER; 在定時前應該先調用QueryPerformanceFrequency()函數獲得機器內部計時器的時鐘頻率。接著在需要嚴格計時的事件發(fā)生前和發(fā)生之后分別調用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"); } 再給出我寫的一個Fibonacci的例子: #include <iostream> #include <cmath> #include <ctime> #include <windows.h> #include<iomanip> 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); //設置為始終輸出小數點后的數字,就是說 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<<setprecision(8)<<setiosflags(ios::showpoint)<<time1<<endl; QueryPerformanceFrequency(&nFreq); QueryPerformanceCounter(&nBeginTime); result2 = Fib2(fib_num); QueryPerformanceCounter(&nEndTime); time2=(double)(nEndTime.QuadPart-nBeginTime.QuadPart)/(double)nFreq.QuadPart; cout<<"Fib2: "<< fixed<<setprecision(20)<<setiosflags(ios::showpoint)<<time2<<endl; cout<<"Fib2 cost "<<time2*(unsigned long)100/time1<<"% time of Fib1."<<endl; //cout << "Hello world!" << endl; return 0; }
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。