编写so库

http://knuth.bokee.com/
Shared Object Library[@more@]

在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:%fn",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,"%fn",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查看

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69498/viewspace-900653/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/69498/viewspace-900653/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值