精确时间计时QueryPerformanceCounter,QueryPerformanceFrequency

来源:互联网 发布:电子数据的作用 编辑:程序博客网 时间:2024/05/20 19:49
精确的时间计时,有时候是非常必要的。比如播放多媒体时视频与音频的时间同步,还有在测试代码的性能时,也需要使用到非常精确的时间计时。还有测试硬件的性能时,也需要精确的时间计时。这时就需要使用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);           }    } 


原创粉丝点击