我正在尝试捕获IPython笔记本魔术函数的结果对象。特指%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的结果。
一个名为TimeitResult的结果对象是由%timeit生成的,但我不知道如何从笔记本中访问它。
我想要一个更干净的解决方案,而不是使用sys.stdout技巧手动捕获标准输出(这段代码将是演示文稿的一部分,因此我试图尽可能地保持它的直率)。有人有什么想法吗?
发布于 2014-08-13 15:15:37
在链接到的源文件中,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将引用返回的结果对象(提示:在对象上使用选项卡完成,它将显示它具有的属性)。
发布于 2017-09-09 16:23:03
使用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
发布于 2019-12-04 16:02:50
补充@dsemi的答案:使用-o将timeit结果保存到变量中,例如:
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)https://stackoverflow.com/questions/25289437
复制相似问题