Linux C | 时间测量

来源:互联网 发布:网络安全工程师学什么 编辑:程序博客网 时间:2024/04/28 18:54

关键函数

int gettimeofday(struct timeval *tv,struct timezone *tz);

gettimeofday 将时间保存在结构 tv 之中.tz 一般我们使用 NULL 来代替.

strut timeval {
long tv_sec; /* 秒数 */
long tv_usec; /* 微秒数 */
};

这个程序输出函数的执行时间,我们可以使用这个来进行系统性能的测试,或者是函数算法的效率分析.
在我机器上的一个输出结果是: Used Time:0.053519

#include <sys/time.h>#include <stdio.h>#include <math.h>void function(){unsigned int i,j;double y;for(i=0;i<1000;i++)for(j=0;j<1000;j++)y=sin((double)i);}main(){struct timeval tpstart,tpend;float timeuse;gettimeofday(&tpstart,NULL);function();gettimeofday(&tpend,NULL);timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;timeuse/=1000000;printf("Used Time:%f\n",timeuse);exit(0);}