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

如果只是初步统计或比较各函数的运行时间,可以用以下方法,若是想详细统计项目中各个函数时间,建议使用第三方工具

一. 使用time 命令

例如编译一个hello.c文件

#gcc hello.c -o hello

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

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

real    0m2.913s
user    0m0.012s
sys     0m0.508s
  • 1
  • 2
  • 3

二. 使用clock()函数统计

#include<stdio.h>           
#include <time.h>               /*要包含的头文件*/

int main(int argc, char *argv[])
{
    /* Init  */
    clock_t start, end;
    start = clock();           /*记录起始时间*/

    printf("time calc test\n");
/*
    *
    *
    * 函数进行的一些列操作
    *
    * */

    /* Final Status */
    end = clock();           /*记录结束时间*/
    {
        double seconds  =(double)(end - start)/CLOCKS_PER_SEC;
        fprintf(stderr, "Use time is: %.8f\n", seconds);
    }
    return 0;
}
运行结果:
# time ./helloTest
time calc test
Use time is 0.00003100

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

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

三. 优缺点对比

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

猜你喜欢

转载自blog.csdn.net/llljjlj/article/details/80148219