linux下统计程序/函数运行时间(转)

一. 使用time 命令

例如编译一个hello.c文件

#gcc hello.c -o hello

生成了hello可执行文件,此时统计该程序的运行时间便可以使用如下命令

#time ./hello 
在程序运行结束后便会显示出所需时间

real    0m2.913s
user    0m0.012s
sys     0m0.508s

二. 使用clock()函数统计

 1 #include<stdio.h>           
 2 #include <time.h>               /*要包含的头文件*/
 3 
 4 int main(int argc, char *argv[])
 5 {
 6     /* Init  */
 7     clock_t start, end;
 8     start = clock();           /*记录起始时间*/
 9 
10     printf("time calc test
");
11 /*
12     *
13     *
14     * 函数进行的一些列操作
15     *
16     * */
17 
18     /* Final Status */
19     end = clock();           /*记录结束时间*/
20     {
21         double seconds  =(double)(end - start)/CLOCKS_PER_SEC;
22         fprintf(stderr, "Use time is: %.8f
", seconds);
23     }
24     return 0;
25 }

运行结果:
# time ./helloTest
time calc test
Use time is 0.00003100

real    0m0.003s
user    0m0.000s
sys     0m0.000s

CLOCKS_PER_SEC用于将clock()函数的结果转化为以秒为单位的量

三. 优缺点对比

time命令在不修改代码的情况下记录程序运行时间,但是,从上面对比可看出time命令统计的结果比较粗糙。 
另外,time命令,统计的结果包涵程序加载和退出的时间。因此,若想得出函数运行时间较为准确的结果,建议使用clock()函数。 
若想了解整个项目中各个函数的运行时间,以期获得性能提升,建议使用——开源工具

转自:http://blog.csdn.net/davie1love/article/details/47087475

原文地址:https://www.cnblogs.com/zl1991/p/7412579.html