0

So I am working on comparing the iterative and recursive ways of finding fibonacci numbers. I wanted to pass them both into timeit, but am having trouble formatting my calls to timeit. Good someone give me a little guidance please? Thanks!

    import timeit

def it_fib(n):
    total = 0
    while n > 0:
        total += n
        n -= 1
    return total

def rec_fib(n):
    if n == 0:
        return 0
    else:
        return n + rec_fib(n-1)

#print (it_fib(10))
#print (rec_fib(10))

print timeit.timeit("it_fib(n)", number = 1000000)
print timeit.timeit("rec_fib(n)", number = 1000000)
T.Def
  • 129
  • 2
  • 6

1 Answers1

0

timeit.timeit can take a function or a string. For script use, the function is usually more convenient:

print timeit.timeit(lambda: it_fib(10))
print timeit.timeit(lambda: rec_fib(10))
nneonneo
  • 171,345
  • 36
  • 312
  • 383