高精度计算代码的运行时间

今天项目中需要计算一个模块的运行时间,要求精度尽可能的高

原来一直使用GetTickCount()函数,如下:

  
  
  
  
  1. DWORD dwStart = GetTickCount();
  2.  
  3. //这里添加需要测试时间的代码模块
  4.  
  5. DWORD dwEnd = GetTickCount();
  6. DWORD dtime = dwEnd - dwStart; 
  7. printf("\n\n%d ms\n\n",d); 

网上虽然说这个函数达到了ms级,但是还是不够,后来经过查找msdn找到一组精度更高的函数

  
  
  
  
  1. QueryPerformanceFrequency(); 
  2. QueryPerformanceCounter(); 

用法如下:

  
  
  
  
  1. LARGE_INTEGER litmp; 
  2. LONGLONG QPart1,QPart2; 
  3. double dfMinus,dfFreq,dfTim; 
  4.  
  5. QueryPerformanceFrequency(&litmp); 
  6. dfFreq = (double)litmp.QuadPart; 
  7. QueryPerformanceCounter(&litmp); 
  8. QPart1 = litmp.QuadPart; 
  9.  
  10.  //这里添加需要测试的代码模块
  11.  
  12. QueryPerformanceCounter(&litmp); 
  13. QPart2 = litmp.QuadPart; 
  14. dfMinus =(double)(QPart2 -QPart1); 
  15. dfTim = dfMinus/dfFreq; 
  16. cout<<dfTim<<endl; 


注:虽然下面这组函数看上去精度非常的高,但是他是平台相关性,即windows 9x之后的平台,支持高精度的

系统才行,使用时候别忘记了加上 #include <windows.h>

 

你可能感兴趣的:(职场,高精度,休闲,计算代码,etTickCount)