%time %timeit
要在ipython下才可以使用。(所以说Jupyter Notebook当然是可以用的,pycharm里的python环境也是jupyter Notebook的)
%time可以测量一行代码执行的时间
%timeit可以测量一行代码多次执行的时间
网上有说法说,%timeit是测量一行代码100000次循环内,3次最快速度的平均值,就像下面这样:
strings = ['foo', 'foobar', 'baz', 'qux', 'python', 'Guido Van Rossum'] * 100000
%time method1 = [x for x in strings if x.startswith('foo')]
CPU times: user 0.19 s, sys: 0.00 s, total: 0.19 s
Wall time: 0.19 s
%time method2 = [x for x in strings if x[:3] == 'foo']
CPU times: user 0.09 s, sys: 0.00 s, total: 0.09 s
Wall time: 0.09 s
%timeit [x for x in strings if x.startswith('foo')]
10 loops, best of 3: 159 ms per loop
%timeit [x for x in strings if x[:3] == 'foo']
10 loops, best of 3: 59.3 ms per loop
但是现在去跑时,已经不是这个效果了:
strings = ['foo', 'foobar', 'baz', 'qux', 'python', 'Guido Van Rossum'] * 100000
%time method1 = [x for x in strings if x.startswith('foo')]
Wall time: 96.7 ms
%time method2 = [x for x in strings if x[:3] == 'foo']
Wall time: 66.8 ms
%timeit [x for x in strings if x.startswith('foo')]
115 ms ± 15.3 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit [x for x in strings if x[:3] == 'foo']
69.1 ms ± 4.33 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
应该是产生了变化,现在的效果应该是测了7轮,每轮10次,取平均。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)