计算程序执行时间的方法

计算程序执行时间的方法
 
 
    在程序设计过程中,往往要计算关键算法的程序执行时间,以考查时间复杂度。这是一个基础知识,但是可以以该主题为点,进行深入分析。本文就是要探讨这些方法的优缺点,以及适用环境。算是一个小的功能模块,为以后的程序设计提供支持。
 

 
2007-10-15
 
方法一:使用clock函数
 

NOTES        The C standard allows for arbitrary values at the start of the program;        subtract the value returned from a call to clock() at the start of the        program to get maximum portability.        Note that the time can wrap around. On a 32bit system where        CLOCKS_PER_SEC equals 1000000 this function will return the same value        approximately every 72 minutes.        On several other implementations, the value returned by clock() also        includes the times of any children whose status has been collected via        wait() (or another wait-type call). Linux does not include the times        of waited-for children in the value returned by clock(). The times()        function, which explicitly returns (separate) information about the        caller and its children, may be preferable.

 
    值得注意的是,使用clock函数作为计时器,最大为(2^32)us,也就是(2^32)/1000000s。换算成分钟的话,71.6minutes。由此看见,每隔大约72分钟,相当于归零一次,也就是wrap around。
 
    利用该机制测试的是测试部分运行占用的CPU的时间。还有一些细节因素需要注意。
 
模板如下:
 

#include <time.h> #include <stdio.h> int main(void) {         clock_t t_start;   /* start time when test starts */         clock_t t_end;     /* end time when test ends */         t_start = clock(); /* get start time */         /* test code */         t_end = clock();   /* get end time */         /* display result */         printf("time: %.3f s/n", (double)(t_end-t_start)/CLOCKS_PER_SEC);         return 0; }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值