您的位置:首页 > 其它

递归与循环的开销比较,高精度时间函数

2012-07-11 17:46 429 查看
#include <iostream>
using namespace std;
#include <sys/time.h>
long p(long n);
int main()
{

struct timeval start, end;
gettimeofday(&start, NULL);
cout<<p(10)<<endl;
gettimeofday(&end, NULL);
long seconds = end.tv_sec - start.tv_sec;
long useconds = end.tv_usec - start.tv_usec;
long elapsed = seconds*1000*1000 + useconds ;
cout<<elapsed;
return 0;
}

long p(long n){
if (n==1) return 1;
else return n*p(n-1);

}

递归方法实现阶乘。

结果:

3628800

83

------------------

(program exited with code: 0)

Press return to continue

====================================================================

#include <iostream>
using namespace std;
#include <sys/time.h>

int main()
{
long i,n=10;
long sum=1;
struct timeval start, end;
gettimeofday(&start, NULL);
for(i=1;i<=n;i++){sum*=i;}
gettimeofday(&end, NULL);
cout<<sum<<endl;
long seconds = end.tv_sec - start.tv_sec;
long useconds = end.tv_usec - start.tv_usec;
long elapsed = seconds*1000*1000 + useconds ;
cout<<elapsed;

return 0;
}
循环实现阶乘。

结果:

3628800

0

------------------

(program exited with code: 0)

Press return to continue

=================================================================

前者耗时83微秒,后者微妙级别以下。可见递归开销很大。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  null struct include