捕获IPython魔术函数的结果

时间:2014-08-13 14:53:40

标签: python ipython ipython-magic

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

以下代码......

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

t = %timeit say_hello(5)

打印到stdout:

1 loops, best of 3: 5 s per loop

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

%timeit生成一个名为TimeitResult的结果对象,但我无法弄清楚如何从Notebook中访问它。

我想要一个更清晰的解决方案,而不是使用sys.stdout技巧手动捕获标准输出(此代码将成为演示文稿的一部分,所以我试图尽可能地保持它直接)。有人有什么想法吗?

3 个答案:

答案 0 :(得分:11)

在您链接到的源文件中,docstring显示运行timeit magic函数的选项;其中一个是返回一个对象结果:

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

所以,如果你运行

obj = %timeit -o somefunc()

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

答案 1 :(得分:1)

使用TimeItResult输出的示例:

sheet.UsedRange.AutoFilter 1, RGB(255,255,0), xlFilterCellColor

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

答案 2 :(得分:0)

补充@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)