您的位置:首页 > 运维架构 > Linux

linux下计算程序运行时间

2014-08-14 16:01 281 查看
这里介绍一下我在项目测试中用到的两种方法

1 clock()

1
#include
<stdio.h>

2
#include
<stdlib.h>

3
#include
<time.h>

4

5
int
main()

6
{

7
   clock_t begin, end;

8
  
double cost;

9
   begin
= clock();

10
  
/* 程序代码
*/

11
   end
= clock();

12
   cost
= (double)(end
- begin)
/ CLOCKS_PER_SEC;

13
   printf("%lf
seconds\n", cost);

14
  

15
  
return
0;

16
}

这个函数返回开启进程和调用clock()之间的的CPU时钟计时单元(clock
tick)数,在MSDN中称之为挂钟时间(wal-clock),每过千分之一秒(1毫秒),调用clock()函数返回的值就加1。

两个缺点:第一是精度,只能精确到1ms,低于1ms的程序全部输出0ms,因为WinNT的时间精度最小是1ms;第二是准确度,printf()的速度太快了,基本上和clock()的速度一样,所以误差很大

2 gettimeofday()
1
#include
<stdio.h>

2
#include
<stdlib.h>

3
#include
<sys/time.h>

4

5
/*struct
timeval说明

6
strut timeval { . {! K( J, c4 ?' }$ _+ L& B0 P

7
long tv_sec; /* 秒数
*/ ( r*
A) \" h& k( j. a2 F4 R

8
long
tv_usec; /* 微秒数
*/

9
( G#
~7
l7 i; I7 t%
~( `};*/

10
int
main()

11
{

12
  
struct timeval tpstart,tpend;

13
  
float timeuse;

14
   gettimeofday(&tpstart,NULL);

15
  
/* 程序代码
*/

16
   gettimeofday(&tpend,NULL);

17
   timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;

18
   timeuse/=1000000;

19
   printf("Used
Time:%f\n",timeuse);

20
  
return
0;

21
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: