您的位置:首页 > 运维架构 > Linux

Linux下测试程序运行时间方法

2011-06-03 13:07 232 查看
(转自:http://linux.chinaitlab.com/command/718537.html)

方法一:有时候我们要计算程序执行的时间.比如我们要对算法进行时间分析

..这个时候可以使用下面这个函数.
 
 

#include <sys/time.h>

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

strut timeval {

long tv_sec; /* 秒数 */

long tv_usec; /* 微秒数 */

};

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

#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);

}

这个程序输出函数的执行时间,我们可以使用这个来进行系统性能的测试,或者是函数算

法的效率分析.在我机器上的一个输出结果是: Used
Time:0.556070

 
 
方法二:第二种是我自己经常用的,就是:

在执行程序前,加time,如:输入time./abc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息