簡體   English   中英

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

[英]Inconsistency between %time and %timeit in IPython

我遇到了一個我無法解釋的奇怪情況。 這是我的測試時間生成一大堆元組:

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上測試過。)

主要的區別是因為“ 默認情況下,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.

貝努瓦,

如果我使用Python 2.6.6和IPython 0.10,那么我會看到類似的答案。 使用Python 2.7.1和IPython 0.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模塊文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM