

NaCl's Blog
source link: https://fredxxx123.wordpress.com/2007/04/08/%e9%ab%98%e7%b2%be%e5%ba%a6%e8%a8%88%e6%99%82%e5%99%a8/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

高精度計時器
我想,大多數的人都只用到 GetTickCount 這個函式吧?
(好啦!只有我是這樣啦!)
我在書上看過的也只有它咩…(畫圓圈)
除了 GetTickCount 之外,最常用的應該就是 timeGetTime 和 QueryPerformanceCounter 吧!
這三種的精準度眾說紛紜,在我電腦上對 GetTickCount 和 timeGetTime 做出來的準度都在 1ms
至於 QueryPerformanceCounter 就很明顯的可以到毫毫…秒(這是誇示法)
所以準到哪裡就看個人吧~
1. timeGetTime
和 GetTickCount 資料型態都是 DWORD ,用法也很簡單
但是,需要包含 <mmsystem.h> 和連結 winmm.lib
連結的方式嘛~
(1)加入程式碼
#pragma comment(lib,"winmm.lib")
(2)從VC裡面調整
專案(P) → 屬性(P) → 組態屬性 → 連結器 → 輸入 → 其他相依性
加入 winmm.lib 即可
有部份文章提到另外兩個搭配使用的函數 timeBeginPeriod 和 timeEndPeriod
好像是可以調整精確度的,但是我電腦上測試沒反應
所以這邊就不另作說明哩!
一個簡單的 Delay 函數:
void DelayByGetTime(DWORD delay)
{
timeBeginPeriod(100);
DWORD TempTime, StartTime, DelayTime;
DelayTime = delay;
StartTime = timeGetTime();
cout << "起始: " << StartTime << endl;
do
{
TempTime = timeGetTime();
if (TempTime < StartTime)
StartTime = TempTime;
} while( (TempTime – StartTime) < DelayTime );
cout << "結束: " << TempTime << endl;
timeEndPeriod(100);
}
2. QueryPerformanceCounter
這個計時器是隨著系統有著不同的精準度
而 QueryPerformanceCounter 使用的資料型態是 LARGE_INTEGER
LARGE_INTEGER 裡便包含了:
LowPart
Low-order 32 bits.
HighPart
High-order 32 bits.
u
LowPart
Low-order 32 bits.
HighPart
High-order 32 bits.
QuadPart
Signed 64-bit integer.
如果編譯器支援 64-bit ,就使用 QuadPart 。不支援時,使用 LowPart 和 HighPart 去表示 QuadPart
(不太確定是不是這意思,詳見 LARGE_INTEGER )
QueryPerformanceCounter 通常要和 QueryPerformanceFrequency 才能計算時間
QueryPerformanceCounter 取得到目前為止的次數
QueryPerformanceFrequency 取得計時器的頻率(次數/秒),目前我的是 3579545 次/秒
照這樣計算的話,大概可以計算到毫毫秒了吧XD
int main(void)
{
LARGE_INTEGER ThisTime, ThatTime, PinTime;
QueryPerformanceFrequency(&PinTime);
QueryPerformanceCounter(&ThisTime);
Sleep(1111);
QueryPerformanceCounter(&ThatTime);
cout << "起始值: " << ThisTime.QuadPart << endl;
cout << "結束值: " << ThatTime.QuadPart << endl;
cout << "差值: " << ThatTime.QuadPart – ThisTime.QuadPart << endl;
cout << "秒: " << (ThatTime.QuadPart – ThisTime.QuadPart) / PinTime.QuadPart << endl;
PinTime.QuadPart /= 1000;
cout << "毫秒: " << (ThatTime.QuadPart – ThisTime.QuadPart) / PinTime.QuadPart << endl;
PinTime.QuadPart
/= 1000;
cout << "毫毫秒: " << (ThatTime.QuadPart – ThisTime.QuadPart) / PinTime.QuadPart << endl;
system("pause");
return 0;
}
哎呀~在這樣下去我啥時才能寫完程式啊
發佈於 2007/04/08作者 fredxxx123分類 C++
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK