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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值