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
}
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
}
相关文章推荐
- Linux下计算程序运行时间的两种方法
- linux下计算程序运行时间
- 【linux】在终端运行C程序,计算运行的时间
- Linux下计算程序运行时间的两种方法 //代码转载
- (迟到的博客,始终是一个过程)Linux/Unix环境下计算C程序运行时间
- Linux下计算程序运行时间的两种方法
- linux 计算程序运行时间
- linux计算程序运行时间
- LINUX计算程序运行时间
- Linux下计算程序运行时间
- linux 下计算程序运行时间 一句话说明
- Linux下计算程序运行时间的一个简单方法
- LINUX下取系统时间(毫秒)和计算程序运行时间
- Linux/Unix环境下计算C程序运行时间
- linux 计算程序运行时间
- Fortran计算程序运行时间总结(windows和linux平台下)
- Linux/Unix环境下计算C程序运行时间
- Linux/Unix环境下计算C程序运行时间
- linux计算程序运行时间
- Linux下计算程序运行时间的一个简单方法