Linux系统C语言计时

https://blog.csdn.net/u013445609/article/details/82971863

  1. #include <stdio.h>
  2. #include <sys/time.h>
  3. #include <math.h>
  4. #include <time.h>
  5. void do_func(){
  6. int k;
  7. for(int i=0;i<1000;i++)
  8. for(int j=0;j<1000;j++)
  9. k=i+j;
  10. }
  11. //int gettimeofday(struct timeval *tv,struct timezone *tz);精度到微秒
  12. long us_timer(){
  13. struct timeval start,end;
  14. gettimeofday(&start,NULL);
  15. do_func();
  16. gettimeofday(&end,NULL);
  17. return (end.tv_sec-start.tv_sec)*10^6+end.tv_usec-start.tv_usec;
  18. }
  19. /*
  20. int clock_gettime(clockid_t clk_id,struct timespec *tp);精确到纳秒
  21. CLOCK_REALTIME:系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时,中间时刻如果系统时间被用户改成其他,则对应的时间相应改变
  22. CLOCK_MONOTONIC:从系统启动这一刻起开始计时,不受系统时间被用户改变的影响
  23. CLOCK_PROCESS_CPUTIME_ID:本进程到当前代码系统CPU花费的时间
  24. CLOCK_THREAD_CPUTIME_ID:本线程到当前代码系统CPU花费的时间
  25. */
  26. long ns_timer(){
  27. struct timespec start,end;
  28. clock_gettime(CLOCK_MONOTONIC,&start);
  29. do_func();
  30. clock_gettime(CLOCK_MONOTONIC,&end);
  31. return (end.tv_sec-start.tv_sec)*10^9+end.tv_nsec-start.tv_nsec;
  32. }
  33. int main(){
  34. printf("花费时间 : %ld 微秒(us)\n", us_timer());
  35. printf("花费时间 : %ld 纳秒(ns)\n", ns_timer());
  36. return 0;
  37. }

运行结果:

  1. #time ./a.out
  2. 花费时间 : 2016 微秒(us)
  3. 花费时间 : 2563087 纳秒(ns)
  4. real0m0.005s
  5. user0m0.005s
  6. sys0m0.000s
(0)

相关推荐