捕获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
不过,我想把 %timeit say_hello(5)
的结果存到一个变量 t
里。
这个 %timeit
会生成一个叫做 TimeitResult
的对象,但我不知道怎么在Notebook里访问它。
我希望能有个更简单的办法,而不是用 sys.stdout
的一些技巧来手动捕获输出(因为这段代码会用在演示中,所以我想尽量保持简单明了)。有没有人有什么好主意?
3 个回答
1
补充一下@dsemi的回答:可以使用 -o
来把 timeit
的结果保存到一个变量里,比如:
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)
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
22
在你链接的源文件中,文档字符串展示了运行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键补全,这样可以看到它有哪些属性)。