14

我正在尝试捕获 IPython Notebook 魔术函数的结果对象。具体来说%timeit

所以下面的代码...

import time
def say_hello(n):
    time.sleep(n)
    print "hello"

t = %timeit say_hello(5)

打印到标准输出:

1 loops, best of 3: 5 s per loop

但是,我想捕获%timeit say_hello(5)变量中的结果t

一个名为的结果对象TimeitResult由 生成%timeit,但我不知道如何从笔记本中访问它。

我想要一个更干净的解决方案,而不是必须使用sys.stdout技巧手动捕获标准输出(此代码将成为演示文稿的一部分,因此我试图使其尽可能直截了当)。有人有想法么?

4

3 回答 3

21

在您链接到的源文件中,文档字符串显示了运行 timeit 魔术函数的选项;其中之一是返回一个对象结果:

-o: return a TimeitResult that can be stored in a variable to inspect
        the result in more details.

所以,如果你跑

obj = %timeit -o somefunc()

obj将引用返回的结果对象(提示:在对象上使用制表符完成,这将向您显示它具有的属性)。

于 2014-08-13T15:15:37.783 回答
1

使用 TimeItResult 输出的示例:

myarray = (3,2,1)
sorttime = %timeit -n1 -r3 -o myarray.sort() 
print(sorttime.best)

在此处查找其他 TimeItResult 属性:https ://ipython.org/ipython-doc/2/api/generated/IPython.core.magics.execution.html

于 2017-09-09T16:23:03.217 回答
1

补充@dsemi 的答案:用于-otimeit结果保存到变量中,例如:

obj = %timeit -o somefunc()

TimeitResult使用选项卡完成时的文档字符串文档显示了可用的属性:

Object returned by the timeit magic with info about the run.

Contains the following attributes :

loops: (int) number of loops done per measurement
repeat: (int) number of times the measurement has been repeated
best: (float) best execution time / number
all_runs: (list of float) execution time of each run (in s)
compile_time: (float) time of statement compilation (s)
于 2019-12-04T16:02:50.410 回答