bad*_*zil 25 python ipython timeit
我遇到了一个我无法解释的奇怪情况.这是我的测试时间生成一大堆元组:
In [1]: def get_list_of_tuples():
...: return [(i,) for i in range(10**6)]
...:
In [2]: %time res = get_list_of_tuples()
CPU times: user 0.93 s, sys: 0.08 s, total: 1.01 s
Wall time: 0.98 s
In [3]: %timeit res = get_list_of_tuples()
1 loops, best of 3: 92.1 ms per loop
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这个大型元组列表的生成只需不到一秒钟.timeit报告执行时间约为0.1秒.为什么这两份报告有这么大的差异?
(在IPython 0.11,Python 2.6.5上测试过.)
bad*_*zil 33
主要的区别是因为" 默认情况下,timeit()会暂时关闭垃圾收集 ".
转动垃圾收集返回的结果类似于问题中显示的结果,即使用垃圾收集执行的时间比没有垃圾收集的时间大:
In [1]: import timeit
# Garbage collection on.
In [2]: N = 10; timeit.timeit('[(i,) for i in range(10**6)]', 'gc.enable()', number=N) / N
Out[2]: 0.74884700775146484
# 749 ms per loop.
# Garbage collection off.
In [3]: N = 10; timeit.timeit('[(i,) for i in range(10**6)]', number=N) / N
Out[3]: 0.15906109809875488
# 159 ms per loop.
Run Code Online (Sandbox Code Playgroud)