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

有帮助吗?

解决方案 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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top