我正在尝试捕获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
技巧手动捕获标准输出(此代码将成为演示文稿的一部分,所以我试图尽可能地保持它直接)。有人有什么想法吗?
答案 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的答案:使用-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)