本博系原创,转载请留言联系
软件工程测试中常常需要统计每个函数的执行时间,某些情况下会出现简单的函数使用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):