0
点赞
收藏
分享

微信扫一扫

Linux系统统计函数时间


本博系原创,转载请留言联系


软件工程测试中常常需要统计每个函数的执行时间,某些情况下会出现简单的函数使用clock测试时间为0的情况,其原因在于clock的精度问题,接下来我们看一下在Linux下一种一微秒为单位统计时间的函数


函数(gettimeofday): 

通过使用gettimeofday函数,我们可以获取微秒级别的时间

int gettimeofday(struct timeval *tv, struct timezone *tz); 其中timeval结构定义如下:
struct timeval
{
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
获取当前时刻,可以精确到微妙级别。
#include <stdio.h>
#include <sys/time.h>
#define MAX 1000 /* the loop count */

/* function: do loop operation
* input: NULL
* output: counter->the counter result
*/
int do_work()
{
int counter = 0; /* the counter */
int i, j; /* the loop variable */

/* accumulate the counter */
for(i = 0; i < MAX; i++)
for(j = 0; j < MAX; j++)
counter++;

/* return the counter's value */
return counter;
}

int main()
{
struct timeval start, end;
int interval;

gettimeofday(&start, NULL);
do_work();
gettimeofday(&end, NULL);

interval = 1000000*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec);

printf("interval = %f/n", interval/1000.0);
}

输出结果如下:

interval = 3.527000

 

real    0m0.006s

user    0m0.000s

sys     0m0.000s

当前任务运行时间为3.527ms。



使用

通过命令gcc -o standard standard.c生成测试程序

通过命令time ./standard来运行测试程序,就可以得到如上的输出结果


PS(clock):



clock()是C/C++中的计时函数,而与其相关的数据类型是clock_t。在MSDN中,查得对clock函数定义如下:


clock_t clock(void) ;


简单而言,就是该程序从启动到函数调用占用CPU的时间。这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元数,在MSDN中称之为挂钟时间;若挂钟时间不可取,则返回-1。其中clock_t是用来保存时间的数据类型。



举报

相关推荐

0 条评论