精確的時間計時,有時候是非常必要的。比如播放多媒體時視頻與音頻的時間同步,還有在測試代碼的性能時,也需要使用到非常精確的時間計時。還有測試硬件的性能時,也需要精確的時間計時。這時就需要使用QueryPerformanceCounter來查詢定時器的計數值,如果硬件裏有定時器,它就會啓動這個定時器,並且不斷獲取定時器的值,這樣的定時器精度,就跟硬件時鐘的晶振一樣精確的。
QueryPerformanceCounter 查詢性能計數器
The QueryPerformanceCounter function retrieves the current value of the high-resolution performance counter, if one exists.
此函數用於獲取精確的性能計數器數值,如果存在.
BOOL QueryPerformanceCounter(
LARGE_INTEGER *lpPerformanceCount // address of current counter value 當前計數器值的地址
);
Parameters
lpPerformanceCount
Points to a variable that the function sets, in counts, to the current performance-counter value. If the installed hardware does not support a high-resolution performance counter, this parameter can be to zero.
指針,指向函數設置的一個變量(一般是個引用,譯者注), 用來返回性能計數器的值.如果已安裝的硬件不支持高精度性能計數器,此參數可以爲0(那調用有什麼意義,用來查詢?).
Return Values
If the installed hardware supports a high-resolution performance counter, the return value is nonzero.
不支持,返回非0
If the installed hardware does not support a high-resolution performance counter, the return value is zero.
否則返回0
下面有個例子:
WINBASEAPI
BOOL
WINAPI
QueryPerformanceCounter(
__out LARGE_INTEGER *lpPerformanceCount
);
WINBASEAPI
BOOL
WINAPI
QueryPerformanceFrequency(
__out LARGE_INTEGER *lpFrequency
);
lpPerformanceCount是返回定時器當前計數值。
QueryPerformanceFrequency是返回定時器的頻率。
調用函數的例子如下:
//精確時鐘查詢。
void TestHighTimer(void)
{
//
LARGE_INTEGER nFreq;
LARGE_INTEGER nLastTime1;
LARGE_INTEGER nLastTime2;
//獲取是否支持精確定時器。
if (QueryPerformanceFrequency(&nFreq))
{
//
const int nBufSize = 256;
TCHAR chBuf[nBufSize];
//顯示定時器的頻率。
wsprintf(chBuf,_T("LastTime=%I64d/r/n"),nFreq);
OutputDebugString(chBuf);
//獲取定時器的值。
QueryPerformanceCounter(&nLastTime1);
wsprintf(chBuf,_T("LastTime=%I64d/r/n"),nLastTime1);
OutputDebugString(chBuf);
Sleep(0);
//獲取定時器的值。
QueryPerformanceCounter(&nLastTime2);
wsprintf(chBuf,_T("LastTime=%I64d/r/n"),nLastTime2);
OutputDebugString(chBuf);
//計算時間是花費多少秒。
float fInterval = nLastTime2.QuadPart - nLastTime1.QuadPart;
swprintf(chBuf,nBufSize,_T("花費:%f/r/n"),fInterval/(float)nFreq.QuadPart);
OutputDebugString(chBuf);
}
}