%time && %timeit 用法
要在ipython下才可以使用。(所以说Jupyter Notebook当然是可以用的,pycharm里的python环境也是jupyter Notebook的)
- %time可以测量一行代码执行的时间
- %timeit可以测量一行代码,多次执行后的平均时间,例如测量一行代码100000次循环内,7次最快速度的平均值。
示例:
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)