2

测量函数执行时间的最佳(精确)方法是什么,例如:

def some_function():
    # ...

我宁愿调用这个函数 1000 次,然后计算平均时间,如下所示:

start = time.time()

for i in range(1000):
    some_function()

elapsed = (time.time() - start)/1000

但也许有更好的方法?

4

2 回答 2

4

我认为你应该使用 timeit 模块

import timeit
t = timeit.Timer('some_function(*args)', # code to run
                 'from __main__ import some_function, args') # initial code 
                                               #run before time measurement
t.timeit(100) # times to run
于 2013-06-04T15:48:22.593 回答
1

我同意 timeit 是在 Python 源代码上运行本机计时的事实上的“模块”。但是,如果您有兴趣在分析方面做一些繁重的工作,您可能会发现类似 runsnakerun 的东西很有用(Python 原生分析器的可视化工具)。

来自 runsnakerun 的片段(实际上只是使用来自 python 分析器的数据):

原始配置文件信息的可排序数据网格视图

身份:函数名、文件名、目录名

花费时间:累计、累计每次、本地和本地每次

整体数据网格视图

(all) callers-of-this-function, (all) callees-of-this-function views

只是为了补充,是的,我知道'主义......你要求一些简单的东西,这太夸张了。但是,如果您以后需要更多信息,我想我会分享另一种可能的解决方案。如果你不觉得它有用,也许其他人会!

要获取将在 runsnakerun 中运行的输出配置文件,请运行以下命令:

$ python -m cProfile -o <outputfilename> <script-name> <options>

或者,如果您在 *nix 中进行开发,您可以使用time,但现在您增加了开销,并且可能会失去 Python 模块timeit可能提供的一些精度。

不同的需求需要不同的解决方案 - 只是增加你的袋子技巧。

高温高压

于 2013-06-04T16:04:48.590 回答