这里介绍一下我在项目测试中用到的两种方法
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 }
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 }
两个缺点:第一是精度,只能精确到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 }
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 }