捕获IPython魔法函数的结果

15

我想捕获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中。 %timeit生成了一个名为TimeitResult的对象,但我无法在Notebook内部访问它。
我希望有比使用sys.stdout技巧手动捕获stdout更清晰的解决方案(这段代码将成为演示的一部分,因此我尽可能地保持简单明了)。 有人有什么想法吗?

你想要输出的字符串还是TimeitResult对象? - dsemi
3个回答

22
在你提供的源文件中,docstring 显示了运行 timeit 魔术函数的选项,其中之一是返回一个对象结果。
-o: return a TimeitResult that can be stored in a variable to inspect
        the result in more details.

因此,如果你运行

obj = %timeit -o somefunc()

obj将引用返回的结果对象(提示:在对象上使用Tab键补全,它会显示对象拥有的属性)。


太棒了,正是我所寻找的! - eric chiang
有没有关于 TimeitResult 对象的文档,这样我就不用使用制表符补全技巧并自己找出所有属性了? - CGFoX
1
找不到任何官方文档,但在 source 的 docstring 中可以看到所有的属性。 - dsemi

1

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接