c++中常用的计算程序运行时间的方法

方法1:

计时函数是clock(),而与其相关的数据类型是clock_t(头文件是time.h)。函数定义原型为:clock_t clock(void);

这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock)。

clock_t是一个长整形数。另外在time.h文件中,还定义了一个常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,因此,我们就可以使用公式clock()/CLOCKS_PER_SEC来计算一个进程自身的运行时间。

给个例子:

 

[c++] view plain copy

  1. #include "stdafx.h"  
  2. #include <time h="">  
  3. #include <iostream>  
  4. using namespace std;  
  5.   
  6.   
  7. int _tmain(int argc, _TCHAR* argv[])  
  8. {  
  9.     clock_t start,end;  
  10.     double totaltime;  
  11.     start = clock();  
  12.     ...//程序主代码  
  13.     end = clock();  
  14.     totaltime = (double)(end - start)/CLOCKS_PER_SEC;  
  15.     cout<<"程序运行时间为:"<<totaltime<<"秒!"<<endl;  
  16.     return 0;  
  17. }  

 

方法2:

使用GetTickCount()函数,头文件是<windows.h>,GetTickCount函数返回从系统运行到现在所经历的时间(类型是DWORD),单位是毫秒,因为DWORD表示范围的限制,所以系统的运行时间表示不能超过DWORD限制。

给个例子:



 

[c++] view plain copy

  1. #include "stdafx.h"  
  2. #include <windows h="">  
  3. //#include <time h="">  
  4. #include <iostream>  
  5. using namespace std;  
  6.   
  7. int _tmain(int argc, _TCHAR* argv[])  
  8. {  
  9.     DWORD start = GetTickCount();  
  10.     ...//程序主代码  
  11.     DWORD end = GetTickCount();  
  12.     cout<<"程序运行时间为:"<<(end - start)<<"毫秒!"<<endl;  
  13.     return 0;  
  14. }  

 

方法3:

time_t类,头文件是<ctime>,精确到秒。

给个例子:

[c++] view plain copy

  1. #include "stdafx.h"  
  2. //#include <windows h="">  
  3. //#include <time h="">  
  4. #include <ctime>  
  5. #include <iostream>  
  6. using namespace std;  
  7.   
  8.   
  9. int _tmain(int argc, _TCHAR* argv[])  
  10. {  
  11.  time_t start = 0,end = 0;  
  12.     time(&start);  
  13.  ...//程序主代码  
  14.  time(&end);  
  15.  cout<<"程序运行时间为:"<<(end - start)<<"秒!"<<endl;  
  16.  return 0;  
  17. }  
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值