如何知道一个函数的运行时间

头文件ctime里面提供了一个函数:  clock_t clock();
 该函数返回的是从程序开始运行到调用clock函数时所打的点数,即clock tick(时钟打点);

2)有一个常数CLK_TCK,是机器时钟每秒所走的时钟打点数,是这样定义的

#define CLK_TCK  CLOCKS_PER_SEC 

# define CLOCKS_PER_SEC 1000

3) 所以,定义两个clock的变量Begin,End;然后在要测试的函数前后分别调用clock函数就可以得出时钟打点数,再除以CLK_TCK就得到时间了

4)我来举个例子具体应用下:

[cpp]  view plain  copy
  1. #include<iostream>    
  2. #include<ctime>    
  3. using namespace std;    
  4. #define N 10000    
  5. #define CLK_TCK  CLOCKS_PER_SEC //机器时钟每秒的打点数    
  6. clock_t Begin,End;    
  7. double duration;    
  8. void Fun(int N);    
  9. void Fun(int N)    
  10. {    
  11.     int i = 0;    
  12.     for(i=0; i<n; i++)    
  13.     {    
  14.         cout<<i<<endl;    
  15.     }    
  16. }    
  17. int main()    
  18. {    
  19.     Begin = clock();    
  20.     Fun(100);    
  21.     End = clock();    
  22.     duration = (End-Begin)/CLK_TCK;    
  23.     cout<<"tick:"<<End-Begin<<endl;    
  24.     cout<<CLK_TCK<<endl;    
  25.     cout<<"duration:"<<duration<<endl;    
  26.     return 0;    
  27. }   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值