一个好的程序员首先要对时间性能很敏感,否则你会容忍程序慢通通的像爬一样。今天在做一个职业测评时,有一个题,大意是写一个函数,函数计算为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; } |
这里看来要好好总结一下。