To expand on thefourtheye's comment (which is correct), you generally want to isolate the steps necessary to define a function into the setup parameter for timeit
. Given your setup, I would do the following:
import timeit as t
def fib_recursive(n):
if n==0:
return 0
elif n == 1:
return 1
else:
return fib_recursive(n-1) + fib_recursive(n-2)
setup = 'from __main__ import fib_recursive'
t.timeit('fib_recursive(29)', setup=setup)
I'll assume that you're aware of the various techniques to improve this algorithm and are choosing to measure its speed to establish a baseline only. You can experiment with the number
keyword parameter to timeit
to control the number of repetitions.