linux下计算程序的运行时间效率,一般有两种方式:
1、使用gettimeofday函数,它主要用来存放当前时间
它的结构为:int gettimeofday(struct timeval *tv,struct timezone *tz);
结构体timeval包含两个参数:
第一个参数结构为:
struct timeval{
long tv_sec;//秒
long tv_usec;//微妙
}
第二个一般为NULL;
使用如下例:
#include
#include
#include
void function()
{
...;
}
int main()
{
struct timeval tStart,tEnd;
gettimeofday(&tStart,NULL);
function();
gettimeofday(&tEnd,NULL);
float timeuse = 1000000*(tEnd.tv_sec - tStart.tv_sec)+ (tEnd.tv_usec -
tStart.tv_usec);//计算时间(将时间转化为微妙)
timeuse /= 1000000;//将时间转化为秒
printf("the function use time = %f\n",timeuse);
return 0;
}
2、是在运行程序时在前面加上time
如:time ./a.out
不过第二种方法只能计算整个程序的运行时间,如果要计算某个程序的运行时间得使用第一种方法;
转载请注明原文地址: https://www.6miu.com/read-25434.html