欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

%time与%timeit

程序员文章站 2022-05-27 23:15:02
...

%time %timeit

要在ipython下才可以使用。
%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次,取平均。

相关标签: python ipython