web-dev-qa-db-ja.com

IPythonの%timeと%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

ご覧のとおり、このタプルの大規模なリストの生成には1秒もかかりません。 timeitは、実行時間が約0.1秒であると報告します。 2つのレポートにこのような大きな違いがあるのはなぜですか?

(IPython 0.11でテスト済み、Python 2.6.5。)

25
badzil

主な違いは、 " デフォルトでは、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.
34
badzil

ブノワ、

Python 2.6.6およびIPython0.10を使用すると、同様の回答が表示されます。Python 2.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
3
Doug Burke