IPython中的%time和%timeit之间不一致

2024-09-28 20:43:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个我无法解释的奇怪情况。下面是我的测试计时生成一个大的元组列表:

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

如您所见,生成这个庞大的元组列表只需不到一秒钟的时间。timeit报告执行时间约为0.1秒。为什么这两份报告有这么大的不同?

(在IPython 0.11和Python 2.6.5上测试。)


Tags: ofin列表gettime报告时间情况
3条回答

贝诺伊特

如果我使用Python 2.6.6和I Python 0.10,那么我会看到与您类似的答案。使用Python2.7.1和iPython0.10.1,我得到了更合理的结果:

% ipython
Python 2.7.1 (r271:86832, Nov  3 2011, 16:23:57) 
Type "copyright", "credits" or "license" for more information.

IPython 0.10.1 -- An enhanced Interactive Python.

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.25 s, sys: 0.10 s, total: 0.35 s
Wall time: 0.35 s

In [3]: %timeit res = get_list_of_tuples()
1 loops, best of 3: 215 ms per loop

%time-只运行一次语句,并且有测量错误

%timeit-多次运行语句,并选择最准确的时间。

有关一些解释,请参见Python timeit module documentation

主要区别在于“by default, timeit() temporarily turns off garbage collection during the timing”。

旋转垃圾回收将返回与问题中显示的结果类似的结果,即使用垃圾回收的执行时间比不使用垃圾回收的执行时间大:

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.

相关问题 更多 >