测试程序运行时间

转载地址:http://blog.csdn.net/lingyin55/article/details/3954668

在平时代码的运行中,度量一段程序效率的快慢一般都是通过计算该段程序运行的时间作为一个衡量的标准,在C中有Clock函数可以帮我们完成这个工作,对于精度要求更高的测量,则可以通过QueryPerformanceFrequency和QueryPerformanceCount来进行。程序很简单,如下:

  1. //利用QueryPerformanceFrequency和QueryPerformanceCounter进行运行时间测试  
  2.   
  3. #include <iostream>  
  4. //#include "time.h"  
  5. #include <windows.h>  
  6.   
  7. using namespace std;  
  8.   
  9. int main( )  
  10. {  
  11.   
  12.   LARGE_INTEGER m_liPerfFreq = {0};  
  13.   QueryPerformanceFrequency( &m_liPerfFreq );  
  14.   
  15.   LARGE_INTEGER m_liPerfStart = {0};  
  16.   QueryPerformanceCounter( &m_liPerfStart );        
  17.     
  18.   for ( int i = 0; i < 100; i++ )  
  19.   {  
  20.     cout   << i <<   endl;  
  21.   }  
  22.     
  23.   LARGE_INTEGER liPerfNow = {0};  
  24.   QueryPerformanceCounter( &liPerfNow );  
  25.   
  26.   int time=( ((liPerfNow.QuadPart - m_liPerfStart.QuadPart) * 1000)/m_liPerfFreq.QuadPart);   
  27.   TCHAR buffer[100];  
  28.   wsprintf(buffer, L"执行时间 %d millisecond   ",time);   
  29.   MessageBox(NULL,buffer, L"计算时间 ",MB_OK);   
  30.   
  31.   return 0;  
  32. }  
   

  1. //利用Clock进行运行时间测试  
  2.   
  3. #include <iostream>  
  4. #include "time.h"  
  5. //#include <windows.h>  
  6.   
  7. using namespace std;  
  8.   
  9. int main( )  
  10. {  
  11.   long start = 0;  
  12.   long end = 0;  
  13.   
  14.   start = clock();  
  15.   for ( int i = 0; i < 100; i++ )  
  16.   {  
  17.     cout   << i <<   endl;  
  18.   }  
  19.   end = clock();  
  20.   
  21.   int time = start - end;  
  22.   TCHAR   buffer[100];  
  23.   wsprintf(buffer, L"執行時間   %d   millisecond   ",time);   
  24.   MessageBox(NULL,buffer, L"計算時間 ",MB_OK);   
  25.   
  26.   return 0;  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值