神奇的命令%timeit非常适合以交互的方式度量代码执行时间。但是,我希望得到%timeit的结果,以便绘制结果。timeit.timeit也允许这样做,但没有自动缩放迭代次数和对%timeit的结果进行规范化。
是否有一个内置函数可以计时一段代码,并自动调整它所执行的迭代次数,并返回一个规范化的结果?
发布于 2016-02-22 21:51:58
神奇的%timeit命令提供了一个-o选项:
-o:返回一个可以存储在变量中的TimeitResult,以便更详细地检查结果。
它仍然会打印结果,但也会返回结果,以便可以在变量中捕获结果。魔术命令的语法有点有限,但是您可以在list中收集不同的结果,方法是将它赋值给变量并将该变量附加到列表中:
res = []
for i in range(3):
a = %timeit -o 10*10
res.append(a)
# 10000000 loops, best of 3: 61 ns per loop
# 10000000 loops, best of 3: 61.1 ns per loop
# 10000000 loops, best of 3: 60.8 ns per loop然后访问res
print(res)
# [<TimeitResult : 10000000 loops, best of 3: 61.2 ns per loop>,
# <TimeitResult : 10000000 loops, best of 3: 61.3 ns per loop>,
# <TimeitResult : 10000000 loops, best of 3: 61.5 ns per loop>]这些结果中的每一个都有几个属性,可能会引起人们的兴趣:
print(res[0].all_runs)
# [0.6166532894762563, 0.6102780388983005, 0.6370787790842183]
print(res[0].best)
# 6.102780388983005e-08
print(res[0].compile_time)
# 0.00020554513866197934
print(res[0].loops)
# 10000000
print(res[0].repeat)
# 3
print(res[0].worst)
# 1.1170931449020795e-06例如,要绘制最佳时间,需要创建一个包含最佳值的新列表:
res_best_times = [result.best * 1e9 for result in res]
# "* 1e9" to get the result in nanoseconds
print(res_best_times)
# [61.2, 61.3, 61.5]发布于 2016-02-23 00:24:35
假设您可以使用/导入IPython,并且您只想创建一个使用%timeit魔术的无头脚本,那么您可以执行如下操作。
假设文件testme.py中有以下内容:
from IPython import get_ipython
def myfun(x):
return x**x
val = 12.3
out = get_ipython().run_line_magic("timeit","-o myfun({})".format(val))
#do something with out, which will be a TimeitResult object然后,您可以非交互地运行脚本:
ipython testme.py发布于 2019-03-13 11:11:44
使用细胞魔术%%
在:
%%timeit -o
res = []
for i in range(5):
a = 10*10
res.append(a)退出:
526 ns ± 44.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
<TimeitResult : 526 ns ± 44.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)>变量下划线“_”存储最后一个表达式值
在:
result = _
result退出:
<TimeitResult : 526 ns ± 44.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)>现在我们可以从属性(help(result))获得更多的数据。
在:
print(result.average) # 2.358365715216288e-06
print(result.stdev) # 5.159462070683934e-07
print(result.timings) #[3.5457100011626608e-06, ..., 2.4937099988164847e-06]
print(result.all_runs) # [0.0003545710001162661, ... 0.00024937099988164846]
print(result.best) # 2.003900021442676e-06
print(result.compile_time) # 0.00030000000000995897
print(result.loops) # 100
print(result.repeat) # 7
print(result.worst) # 3.5457100011626608e-06https://stackoverflow.com/questions/33943362
复制相似问题