Domanda

Trying to figure out how long it takes this piece of code to run:

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)
print fib_recursive(29)
print t.Timer("fib_recursive(29)")

Output was the following:

514229 timeit.Timer instance at 0xda28c0

È stato utile?

Soluzione 2

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.

Altri suggerimenti

When you use IPython, the easiest way for timing is using the magicfunction %timeit:

%timeit fib_recursive(10)
>>> 10000 loops, best of 3: 70.2 us per loop

Use timeit.Timer.timeit:

timer = t.Timer("fib_recursive(29)", setup='from __main__ import fib_recursive')
print timer.timeit()

or simply use timeit.timeit:

print t.timeit("fib_recursive(29)", setup='from __main__ import fib_recursive')

NOTE: You need to pass import statement to setup argument.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top