下面的代码给出了一段测量函数的平均执行时间。
clock_gettime这个函数的精确度要比gettimeofday 高,但是编译的时候,加上 -lrt,否则无法编译通过。
这个方法总体可行,但是Linux下有更好的工具可以分析代码的效率,gprof和Oprofile,本文暂时不讨论着两个工具。这两个工具的讨论留待后面,我的经验更丰富的时候讨论。
- #include<stdio.h>
-
#include<stdlib.h>
-
#include<sys/time.h>
-
#include<time.h>
-
-
#define MILLION (1000000)
-
#define TIMES (1000000)
-
#define BILLION (1000000000)
-
extern int function(int a,int b,int c ,unsigned char* s);
-
-
int main()
-
{
-
int a = 1;
-
int b = 2;
-
int c = 3;
-
int i;
-
-
unsigned char s[128] = {0};
-
struct timespec tpstart;
-
struct timespec tpend;
-
signed long long timeif;
-
signed long long timeif_func;
-
-
-
if(clock_gettime(CLOCK_MONOTONIC,&tpstart))
-
{
-
fprintf(stderr,"Fail to get start time for NULL\n");
-
return -1;
-
}
-
for(i = 0;i<TIMES;i++)
-
{
-
;
-
}
-
-
if(clock_gettime(CLOCK_MONOTONIC,&tpend))
-
{
-
fprintf(stderr,"Fail to get end time for NULL\n");
-
return -1;
-
}
-
-
timeif = BILLION*(tpend.tv_sec - tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec);
-
-
printf("BLANK OP 's average time is %d\n",(timeif)/TIMES);
-
-
-
if(clock_gettime(CLOCK_MONOTONIC,&tpstart))
-
{
-
fprintf(stderr,"Fail to get start time for function \n");
-
return -1;
-
}
-
for(i = 0;i<TIMES;i++)
-
{
-
function(a,b,c,s); //我们测量的函数
-
}
-
-
if(clock_gettime(CLOCK_MONOTONIC,&tpend))
-
{
-
fprintf(stderr,"Fail to get end time for function \n");
-
return -1;
-
}
-
-
timeif_func = BILLION*(tpend.tv_sec - tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec);
-
-
printf(" FUNCTION function's average time is %d ns\n",(timeif_func - timeif )/TIMES);
-
-
}
阅读(3743) | 评论(0) | 转发(0) |