問題描述
我最近決定我的 Timer 類需要從使用毫秒更改為微秒,經過一些研究后,我認為 QueryPerformanceCounter 可能是我最安全的選擇.(Boost::Posix
上的警告說它可能不適用于 Win32 API,這讓我有點失望).但是,我不確定如何實現它.
I recently decided that I needed to change from using milliseconds to microseconds for my Timer class, and after some research I've decided that QueryPerformanceCounter is probably my safest bet. (The warning on Boost::Posix
that it may not works on Win32 API put me off a bit). However, I'm not really sure how to implement it.
我正在做的是調用我正在使用的任何 GetTicks()
esque 函數并將其分配給 Timer 的 startingTicks
變量.然后為了找到經過的時間量,我只需從 startingTicks
中減去函數的返回值,當我重置計時器時,我只需再次調用該函數并將startingTicks 分配給它.不幸的是,從我看到的代碼來看,它并不像調用 QueryPerformanceCounter()
那樣簡單,而且我不確定我應該將什么作為參數傳遞.
What I'm doing is calling whatever GetTicks()
esque function I'm using and assigning it to Timer's startingTicks
variable. Then to find the amount of time passed I just subtract the function's return value from the startingTicks
, and when I reset the timer I just call the function again and assign startingTicks to it. Unfortunately, from the code I've seen it isn't as simple as just calling QueryPerformanceCounter()
, and I'm not sure what I'm supposed to pass as its argument.
推薦答案
#include <windows.h>
double PCFreq = 0.0;
__int64 CounterStart = 0;
void StartCounter()
{
LARGE_INTEGER li;
if(!QueryPerformanceFrequency(&li))
cout << "QueryPerformanceFrequency failed!
";
PCFreq = double(li.QuadPart)/1000.0;
QueryPerformanceCounter(&li);
CounterStart = li.QuadPart;
}
double GetCounter()
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return double(li.QuadPart-CounterStart)/PCFreq;
}
int main()
{
StartCounter();
Sleep(1000);
cout << GetCounter() <<"
";
return 0;
}
這個程序應該輸出一個接近 1000 的數字(windows sleep 不是那么準確,但應該是 999).
This program should output a number close to 1000 (windows sleep isn't that accurate, but it should be like 999).
StartCounter()
函數記錄性能計數器在 CounterStart
變量中的滴答數.GetCounter()
函數返回自 StartCounter()
上次調用以來的毫秒數作為雙精度值,所以如果 GetCounter()
返回 0.001 那么自從 StartCounter()
被調用以來已經過去了大約 1 微秒.
The StartCounter()
function records the number of ticks the performance counter has in the CounterStart
variable. The GetCounter()
function returns the number of milliseconds since StartCounter()
was last called as a double, so if GetCounter()
returns 0.001 then it has been about 1 microsecond since StartCounter()
was called.
如果您想讓計時器使用秒,請更改
If you want to have the timer use seconds instead then change
PCFreq = double(li.QuadPart)/1000.0;
到
PCFreq = double(li.QuadPart);
或者如果你想要微秒那么使用
or if you want microseconds then use
PCFreq = double(li.QuadPart)/1000000.0;
但實際上是為了方便,因為它返回一個雙精度值.
But really it's about convenience since it returns a double.
這篇關于如何使用 QueryPerformanceCounter?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!