Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

分别使用递归方法和非递归方法求斐波那契数列,并比较两者的运行速度(测量代码运行时间)

$
0
0

由运行时间可知,当数据量增大时,递归方法程序运行效率成为瓶颈,速度变得极为缓慢。

#include<cstdio>
#include<iostream>
#include<time.h>
using namespace std;
int Funct( int n )
{
    if(n==0) return 1;
    if(n==1) return 1;
    return Funct(n-1) + Funct(n-2);
}
int Foo( int n ) // n 为非负整数
{
    int first=1;//应该初始化a为1而不是0
    int second=1;
    int first_plus_second;
    if(n==0) first_plus_second=1;
    else if(n==1) first_plus_second=1;
    else for(int i=2;i<=n;i++) //应该n从2开始算起
    {
        first_plus_second=first+second;
        first=second;
        second=first_plus_second;
    }
    return first_plus_second;
}
void testRunningTime()
{
    int n;
    long now=0;
    cout<<"请输入:\n";
    while(cin>>n)
    {
        now=clock();
        cout<<"----   Foo("<<n<<")= "<<Foo(n)<<endl;
        cout<<"----   Foo("<<n<<") running time is :"
            <<(double)(clock()-now)/CLOCKS_PER_SEC<<endl;
        now=clock();
        cout<<"----   Funct("<<n<<")= "<<Funct(n)<<endl;
        cout<<"----   Funct("<<n<<") running time is :"
            <<(double)(clock()-now)/CLOCKS_PER_SEC<<endl;
        cout<<"请继续输入:\n";
    }
}
int main()
{
    testRunningTime();
}
/**************************************************
程序运行结果:
请输入:
1
----   Foo(1)= 1
----   Foo(1) running time is :0
----   Funct(1)= 1
----   Funct(1) running time is :0
请继续输入:
2
----   Foo(2)= 2
----   Foo(2) running time is :0.015
----   Funct(2)= 2
----   Funct(2) running time is :0
请继续输入:
22
----   Foo(22)= 28657
----   Foo(22) running time is :0
----   Funct(22)= 28657
----   Funct(22) running time is :0.015
请继续输入:
33
----   Foo(33)= 5702887
----   Foo(33) running time is :0
----   Funct(33)= 5702887
----   Funct(33) running time is :0.078
请继续输入:
40
----   Foo(40)= 165580141
----   Foo(40) running time is :0
----   Funct(40)= 165580141
----   Funct(40) running time is :1.653
请继续输入:
45
----   Foo(45)= 1836311903
----   Foo(45) running time is :0
----   Funct(45)= 1836311903
----   Funct(45) running time is :18.658
请继续输入:
^Z

Process returned 0 (0x0)   execution time : 70.512 s
Press any key to continue.

***************************************************/


作者:shihui512 发表于2013-6-4 21:59:44 原文链接
阅读:2 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>