Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1605525
  • 博文数量: 585
  • 博客积分: 14610
  • 博客等级: 上将
  • 技术积分: 7402
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-15 10:52
文章存档

2013年(5)

2012年(214)

2011年(56)

2010年(66)

2009年(44)

2008年(200)

分类: C/C++

2011-08-23 10:37:00

标签:  性能优化  分类: algorthm

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

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



#include
#include
#include
#include

#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
{
;
}
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
{
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);
阅读(647) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~