Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3844741
  • 博文数量: 146
  • 博客积分: 3918
  • 博客等级: 少校
  • 技术积分: 8584
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-17 13:52
个人简介

个人微薄: weibo.com/manuscola

文章分类

全部博文(146)

文章存档

2016年(3)

2015年(2)

2014年(5)

2013年(42)

2012年(31)

2011年(58)

2010年(5)

分类: C/C++

2011-07-27 21:44:27

     下面的代码给出了一段测量函数的平均执行时间。
     clock_gettime这个函数的精确度要比gettimeofday 高,但是编译的时候,加上 -lrt,否则无法编译通过。

     这个方法总体可行,但是Linux下有更好的工具可以分析代码的效率,gprof和Oprofile,本文暂时不讨论着两个工具。这两个工具的讨论留待后面,我的经验更丰富的时候讨论。

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<sys/time.h>
  4. #include<time.h>

  5. #define MILLION (1000000)
  6. #define TIMES (1000000)
  7. #define BILLION (1000000000)
  8. extern int function(int a,int b,int c ,unsigned char* s);

  9. int main()
  10. {
  11.         int a = 1;
  12.         int b = 2;
  13.         int c = 3;
  14.         int i;

  15.         unsigned char s[128] = {0};
  16.         struct timespec tpstart;
  17.         struct timespec tpend;
  18.         signed long long timeif;
  19.         signed long long timeif_func;


  20.         if(clock_gettime(CLOCK_MONOTONIC,&tpstart))
  21.         {
  22.             fprintf(stderr,"Fail to get start time for NULL\n");
  23.             return -1;
  24.         }
  25.         for(i = 0;i<TIMES;i++)
  26.         {
  27.             ;
  28.         }
  29.         
  30.         if(clock_gettime(CLOCK_MONOTONIC,&tpend))
  31.         {
  32.             fprintf(stderr,"Fail to get end time for NULL\n");
  33.             return -1;
  34.         }
  35.         
  36.         timeif = BILLION*(tpend.tv_sec - tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec);

  37.         printf("BLANK OP 's average time is %d\n",(timeif)/TIMES);

  38.         
  39.         if(clock_gettime(CLOCK_MONOTONIC,&tpstart))
  40.         {
  41.             fprintf(stderr,"Fail to get start time for function \n");
  42.             return -1;
  43.         }
  44.         for(i = 0;i<TIMES;i++)
  45.         {
  46.             function(a,b,c,s); //我们测量的函数
  47.         }
  48.         
  49.         if(clock_gettime(CLOCK_MONOTONIC,&tpend))
  50.         {
  51.             fprintf(stderr,"Fail to get end time for function \n");
  52.            return -1;
  53.         }
  54.         
  55.         timeif_func = BILLION*(tpend.tv_sec - tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec);

  56.         printf(" FUNCTION function's average time is %d ns\n",(timeif_func - timeif )/TIMES);
  57.         
  58. }
阅读(3675) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~