我在 Ubuntu 上使用 IPython 6.2.1 与 Eclipse/PyDev 的集成。 Python版本为3.5.2。
我经常看到人们为脚本计时,例如
>>>%timeit for _ in range(1000): True
10000 loops, best of 3: 37.8 µs per loop
当我执行同样的操作时,我的输出是
>>>%timeit for _ in range(1000): True
20.8 µs ± 353 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
恕我直言,“最好的 3”是更好的衡量标准,所以我想更改我的输出。
我都读了,IPython和 Python timeit文档。他们都没有提到,输出可能不同于“三者之最”。这是 Linux/Eclipse/PyDev 实现的问题还是有办法改变 timeit
模块的输出?
P.S.:当我使用 timeit
时,在 Eclipse 控制台中也会发生同样的情况,因此 IPython 在这里可能无关紧要。
>>>timeit '"-".join(str(n) for n in range(100))'
11 ns ± 0.0667 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
Unutbu 指出您可以在程序中实现所需的行为。运行 first script calling timeit.main()
here确实返回了 3 个中最好的一个。但我更喜欢一个可以在 Eclipse 控制台中交互式运行的版本。
最佳答案
显示由 TimeitResult
对象生成(参见 timeit??
代码 list )。使用 -o 选项,我得到了我可以检查的对象:
In [95]: %timeit -o np.einsum('bdc,ac->ab', a, b, optimize=False)
170 µs ± 27.5 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Out[95]: <TimeitResult : 170 µs ± 27.5 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)>
In [96]: res = _
In [97]: print(res)
170 µs ± 27.5 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [98]: vars(res)
Out[98]:
{'_precision': 3,
'all_runs': [1.6981208299985155,
1.6976570829865523,
1.6978941220149864,
1.6976559630129486,
1.6976608499826398,
1.697147795028286,
1.6977746890042908],
'best': 0.0001697147795028286,
'compile_time': 0.0,
'loops': 10000,
'repeat': 7,
'timings': [0.00016981208299985155,
0.00016976570829865524,
0.00016978941220149863,
0.00016976559630129485,
0.00016976608499826398,
0.0001697147795028286,
0.0001697774689004291],
'worst': 0.00016981208299985155}
看起来生成 best of 3
显示的信息仍然存在,但格式化程序不见了。它可能在旧版本中找到。
@property
def average(self):
return math.fsum(self.timings) / len(self.timings)
代码在IPython/core/magics/execution.py
关于python - IPython %timeit 魔术 - 将输出从 "mean & std"更改为 "best of 3",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48733545/