这是计算斐波那契的代码
import timeit
counter=0
def fibhelper(n):
global counter
counter+=1
if n==0 :
return 0
elif n==1:
return 1
else:
return fibhelper(n-1)+fibhelper(n-2)
print fibhelper(20)
print "Total function calls-- ",counter
t1=timeit.Timer('fibhelper(20)',"from __main__ import fibhelper")
y=t1.timeit()
print "normal method in secs: ",y
输出是:
6765
Total function calls-- 21891
它立即出来,但它仍在计算y
。为什么是这样?当function
快速评估时,为什么timeit
需要function
更长的时间?