QueryPerformanceCounter与QueryPerformanceFrequency
可以实现毫秒微秒计时器:
在使用QueryPerformanceCounter之前和之后可得到一个高精度计时器值,然后使用QueryPerformanceFrequency得到每秒滴答数,最后将时差除以这个数可转换为秒。
1 LARGE_INTEGER m_liPerformanceFrequency; 2 QueryPerformanceFrequency( &m_liPerformanceFrequency); 3 4 //... 5 6 LARGE_INTEGER liPerformanceCount; 7 QueryPerformanceCounter( &liPerformanceCount); 8 double dTime = double(liPerformanceCount.QuadPart)/double(m_liPerformanceFrequency.QuadPart);
对于IARGE_INTEGER union,可参考上一篇博文。
QueryPerformanceFrequency的函数原型为BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency),返回硬件是否支持高精度计数器。
QueryPerformanceCounter的函数原型为BOOL QueryPerformanceCounter (LARGE_INTEGER *lpCount)。
下面给出具体例子:
1 #include <windows.h> 2 3 double PCFreq = 0.0; 4 __int64 CounterStart = 0; 5 6 void StartCounter() 7 { 8 LARGE_INTEGER li; 9 if(!QueryPerformanceFrequency(&li)) 10 cout << "QueryPerformanceFrequency failed!\n"; 11 12 PCFreq = double(li.QuadPart)/1000.0; 13 14 QueryPerformanceCounter(&li); 15 CounterStart = li.QuadPart; 16 } 17 double GetCounter() 18 { 19 LARGE_INTEGER li; 20 QueryPerformanceCounter(&li); 21 return double(li.QuadPart-CounterStart)/PCFreq; 22 } 23 24 int main() 25 { 26 StartCounter(); 27 Sleep(1000); 28 cout << GetCounter() <<"\n"; 29 return 0; 30 }
得出结果应该接近windows睡眠了1000s。
如果想要结果以秒为单位输出:
PCFreq = double(li.QuadPart);
或者以微秒为单位输出:
PCFreq = double(li.QuadPart)/1000000.0;
关于QueryPerformanceCounter的细节,msdn给出了文档:在关于时间代码中如何使用QueryPerformanceCounter?