Chinaunix首页 | 论坛 | 博客
  • 博客访问: 335229
  • 博文数量: 121
  • 博客积分: 2771
  • 博客等级: 少校
  • 技术积分: 705
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-01 12:44
文章分类

全部博文(121)

文章存档

2011年(121)

分类: C/C++

2011-04-07 14:13:23

在linux开发中,有很多程序需要在时间上做优化,像XFree86,mozilla等,所以需要有高精度的时间测量方法。下面给出解决方案。

1。基本函数gettimeofday
#include
#include

函数原型:int gettimeofday(struct timeval *tv, struct timezone *tz);
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
struct timezone {
int tz_minuteswest; /* minutes W of Greenwich */
int tz_dsttime; /* type of dst correction */
};

2。测量原理
(1)设置基准点
(2)在每个测试点,获取时间信息,与基准点的时间差值作为优化依据

3。示例程序
#include
#include
void consume()
{
unsigned int i,j;
double y;
for(i=0;i<1000;i++)
for(j=0;j<1000;j++)
y=i*j;
}

main()
{
struct timeval tpstart,tpend;
float timeuse;

gettimeofday(&tpstart,NULL);
function();
gettimeofday(&tpend,NULL);
timeuse=(tpend.tv_sec-tpstart.tv_sec)+
((float)tpend.tv_usec-(float)tpstart.tv_usec)/(1000000);
printf("Used Time:%f\\n",timeuse);
}


4。编写测量库
头文件anthony_timedebug.h:
#ifndef _ANTHONY_TIMEDEBUG_H
#define _ANTHONY_TIMEDEBUG_H

#ifdef __cplusplus
extern "C"
{
#endif

#include
#include
#include

void timedebug_setstart();
void timedebug_getcurrent();


#ifdef __cplusplus
}
#endif

#endif
源文件:anthony_timedebug.c
#include "anthony_timedebug.h"

struct timeval tpstart;

void timedebug_setstart()
{
gettimeofday(&tpstart,NULL);
}


void timedebug_getcurrent()
{
FILE *fp;
struct timeval tpend;
float used;

gettimeofday(&tpend,NULL);

used = (tpend.tv_sec-tpstart.tv_sec)+
((float)tpend.tv_usec-(float)tpstart.tv_usec)/(1000000);

fp = fopen("/tmp/timedebug.log","a");
if(fp)
{
fprintf(fp,"%f\\n",used);
fclose(fp);
}
}

编译目标文件:
gcc -fPIC -c anthony_timedebug.c
编译库:
gcc -shared -Wl,-soname,libanthony.so.1 -o libanthony.so.1.0.1 anthony_timedebug.o -lc
安装:
cp anthony_timedebug.h /usr/include
cp libanthony.so.1.0.1 /usr/lib
cd /usr/lib
ln -s libanthony.so.1.0.1 libanthony.so
ldconfig

5.测试
测试程序test.c:
#include

void consume()
{
int i,j;
for(i=0;i<10000;i++)
for(j=0;j<10000;j++);
}

main()
{
timedebug_setstart();
consume();
timedebug_getcurrent();
}
编译:
gcc -o test test.c -lanthony
执行结果可以在/tmp/timedebug.log查看

阅读(1663) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~