捕获IPython魔术函数的结果



我正在尝试捕获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

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

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

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

在您链接到的源文件中,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将引用返回的结果对象(提示:在对象上使用制表符完成,这将显示它具有的属性)。

使用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

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

obj = %timeit -o somefunc()

TimeitResult的docstring文档在使用制表符完成时显示了可用的属性:

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)

最新更新