程序运行时间

    一个好的程序员首先要对时间性能很敏感,否则你会容忍程序慢通通的像爬一样。今天在做一个职业测评时,有一个题,大意是写一个函数,函数计算为fun(n)=fun(n-1)+fun(n-2)+n,求fun(39)+fun(25)。这个就像兔子数列一样,有递归和迭代的两种求法。我看了一下,只要你求fun(39)和fun(25)这个函数值,并且变量的值比较小。故用递归写了。结果发现速度其慢。于是将递归函数调用的次数打印出来,当时晕了,1千多万次,费时2秒。

#include<stdio.h>
#include<time.h>
int      foo( int n );
int c    ount = 0 ;
clock_t  tm_s, tm_e;
int main()
{
   int s = 0 ;
   tm_s = clock();
   s  = foo(39) ;
   s  += foo(25);
   tm_e = clock();
   printf("%d,%d\n",s,count);
   printf("take time:%d\n",(tm_e - tm_s)/1000);
   return 0;
}


int foo( int n )
{
   count++;
   if ( n == 1  || n == 2 )
   {
     return n+1;
   }
   return foo(n-1) + foo(n-2) + n ;
}

而用迭代的方法,却在几乎为0的时间下完成啦。



#include<stdio.h>
#include<time.h>
int count = 0 ;
int a[40] ;
clock_t  tm_s, tm_e;
int main()
{
    int i ;
    tm_s = clock();
    a[0] = 0 ;
    a[1] = 2 ;
    a[2] = 3 ;
    for ( i = 3 ; i < 40 ; i ++ )
    {
         a[i] = a[i-1] + a[i-2] + i ;
    }
    tm_e = clock();
    printf("%d\n",a[39]+a[25]);
    printf("take time:%d\n",(tm_e - tm_s)/1000);
    return 0;
}

这里看来要好好总结一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值