简体   繁体   English

你如何使用timeit来计算一个函数运行多长时间?

[英]How do you use timeit to time how long it takes a function to run?

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 514229 timeit.Timer实例位于0xda28c0

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 . 要扩展thefourtheye的注释(这是正确的),您通常希望将定义函数所需的步骤隔离到timeit的setup参数中。 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. 您可以尝试使用number关键字参数来timeit以控制重复次数。

When you use IPython, the easiest way for timing is using the magicfunction %timeit : 当你使用IPython时,最简单的计时方法是使用magicfunction %timeit

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

Use timeit.Timer.timeit : 使用timeit.Timer.timeit

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

or simply use timeit.timeit : 或者只是使用timeit.timeit

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

NOTE: You need to pass import statement to setup argument. 注意:您需要将import语句传递给setup参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM