首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

函数运作时间计算

2013-11-09 
函数运行时间计算在最近的工作中,遇到了需要查看某些函数运行具体时间的需求,现在分享给大家,如果有更好的

函数运行时间计算

在最近的工作中,遇到了需要查看某些函数运行具体时间的需求,现在分享给大家,如果有更好的改进,大家相互交流,这里只做抛砖引玉的作用。

既然要想计算时间,那么就必须知道如何计算时间,这里选用的计算时间的函数为

/**
 * do_gettimeofday - Returns the time of day in a timeval
 * @tv: pointer to the timeval to be set
 *
 * NOTE: Users should be converted to using getnstimeofday()
 */
void do_gettimeofday(struct timeval *tv)
{
struct timespec now;


getnstimeofday(&now);
tv->tv_sec = now.tv_sec;
tv->tv_usec = now.tv_nsec/1000;
}

这里面有个重要的结构体

struct timeval {
__kernel_time_ttv_sec; /* seconds */
__kernel_suseconds_ttv_usec; /* microseconds */
};

这样我们就能够得到次结构体的秒数和微秒数。而具体下面的函数是如何得到的我们无需关心。

我们只要定义一些变量,并且在函数的前后加上次函数即可得到函数的具体执行时间。定义变量和添加函数的方法如下:

         do_gettimeofday(&tva);

functions()


do_gettimeofday(&tvb);
count_time += delta(&tva, &tvb);
printk(KERN_INFO"sync_inodes_sb cost %lu microseconds\n",count_time);

这样我们便能够计算并打印此函数的总的执行时间,而这里在内核中并没有提供我们这样的delta函数,那我们自己动手定义一下吧:

static long delta(struct timeval *tv1,struct timeval *tv2)
{
unsigned long deltv;

deltv = tv2->tv_sec - tv1->tv_sec;

deltv = deltv*1000000 + tv2->tv_usec - tv1->tv_usec;

return deltv;
}

这样我们就能够完美的计算functions的执行时间了。

热点排行