计算函数的执行时间是基本功

1. 思路

我们在执行函数前后分别记录下时间戳,然后计算两个时间戳的差值即可。

我们需要借助函数clock_gettime来实现这个功能。看下该函数的定义:


  1. #include <time.h> 
  2.  
  3. int clock_gettime(clockid_t clk_id, struct timespec* tp); 
  4.  
  5. 可以根据需要,获取不同要求的精确时间 
  6.  
  7. 参数: 
  8. clk_id :  
  9.  检索和设置的clk_id指定的时钟时间。 
  10.  CLOCK_REALTIME:系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时,中间时刻如果系统时间被用户改成其他,则对应的时间相应改变 
  11.   CLOCK_MONOTONIC:从系统启动这一刻起开始计时,不受系统时间被用户改变的影响 
  12.   CLOCK_PROCESS_CPUTIME_ID:本进程到当前代码系统CPU花费的时间 
  13.   CLOCK_THREAD_CPUTIME_ID:本线程到当前代码系统CPU花费的时间 
  14. tp :  
  15.  获取的时间戳会存放到该结构体变量中 
  16.  struct timespec 
  17.  { 
  18.          time_t tv_sec; /* 秒*/ 
  19.          long tv_nsec; /* 纳秒*/ 
  20.  }; 
  21. 返回值: 
  22.  成功  0 
  23.  失败 -1  ,同时errno会被赋值 

因为我们希望计算执行某个函数的时间,所以我们第一个参数选择CLOCK_MONOTONIC。

2. 实例1

我们先来实现一个简单的程序:


  1.  1 #include <stdio.h>                                                                
  2.  2 #include <stdlib.h> 
  3.  3 #include <stdint.h> 
  4.  4 #include <time.h> 
  5.  5 #include <sys/time.h> 
  6.  6 #include <sys/stat.h> 
  7.  7 #include <sys/types.h> 
  8.  8 #include <unistd.h> 
  9.  9 #include <string.h> 
  10. 10  
  11. 11 int main() 
  12. 12 { 
  13. 13     int rc; 
  14. 14     struct timespec ts_start, ts_end; 
  15. 15      
  16. 16     //start time before call function 
  17. 17     rc = clock_gettime(CLOCK_MONOTONIC, &ts_start); 
  18. 18      
  19. 19     printf("you can call your function here\n"); 
  20. 20      
  21. 21     //end time before call function  
  22. 22     rc = clock_gettime(CLOCK_MONOTONIC, &ts_end); 
  23. 23      
  24. 24     printf("CLOCK_MONOTONIC reports %ld.%09ld seconds\n"
  25. 25             ts_end.tv_sec – ts_start.tv_sec, ts_end.tv_nsec – ts_start.tv_nsec); 
  26. 26 } 

19行 我们可以将自己要执行的函数放置在此处。

编译


  1. gcc runtime.c -lrt 

注意需要增加动态链接库lrt,函数clock_gettime()定义于该库中。

执行结果如下:


  1. root@ubuntu:/home/peng/zhh# ./a.out  
  2. you can call your function here 
  3. CLOCK_MONOTONIC reports 0.000013689 seconds 
【声明】:芜湖站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

相关文章