windows下的精确计时函数

来源:互联网 发布:石家庄创客儿童编程 编辑:程序博客网 时间:2024/05/01 12:42

BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency)获取系统的计数器的频率

BOOL QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount)获取计数器的值
(原文出处:coder_xia的博客:http://blog.csdn.net/coder_xia/article/details/6566708)

   然后用两次计数器的差除以Frequency就得到时间。

测试程序如下:

[c-sharp] view plaincopy
  1. #include <iostream>  
  2. #include <windows.h>  
  3. using namespace std;  
  4. int main()  
  5. {  
  6.     LARGE_INTEGER m_nFreq;  
  7.     LARGE_INTEGER m_nBeginTime;  
  8.     LARGE_INTEGER nEndTime;  
  9.     QueryPerformanceFrequency(&m_nFreq); // 获取时钟周期  
  10.     QueryPerformanceCounter(&m_nBeginTime); // 获取时钟计数  
  11.     Sleep(100);  
  12.     QueryPerformanceCounter(&nEndTime);  
  13.     cout << (double)(nEndTime.QuadPart-m_nBeginTime.QuadPart)*1000/m_nFreq.QuadPart << endl;  
  14. }  
 

需要注意的就是结果需要强制转换为double,不然会得到如下错误:<< is ambiguous


原创粉丝点击