递归与循环的开销比较,高精度时间函数
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微秒,后者微妙级别以下。可见递归开销很大。
相关文章推荐
- 数组求和(递归和循环)函数 时间性能测量(最差情形)
- 【郝斌数据结构自学笔记】53-56_一个函数为什么可以自己调用自己_递归必须满足三个条件_循环和递归的比较
- js 时间函数应用加、减、比较、格式转换的示例代码
- js日期时间比较函数
- 【算法】递归与while循环的通俗比较
- GPU上和CPU上执行函数时间比较
- DateDiff 函数的用法 SQL时间比较 (转自八度空间)
- 递归的效率问题及递归与循环比较
- 比较“+”,insert( )和append( )的速度,利用循环向列表中增加10000个元素,比较几种方法的运行时间。
- 递归求和(Recursive)与for循环求和效率问题的简单比较
- 函数及递归《算法入门经典》第四章(由于能力和时间有限没有做习题)
- PHP isset()与empty()函数执行时间比较
- Hibernate中HQL函数汇总及获取当前时间进行比较举例
- 9.10 编写并测试Fibonacii函数,该函数用循环代替递归计算斐波那契数。
- 前台js时间函数比较
- js日期时间比较函数
- 使用C++标准库sort自定义比较函数导致死循环问题
- js 时间比较函数
- python第一站-列表,循环,函数,递归
- Mysql 时间比较函数