比較Python 2 和 Python 3 在對list進行迴圈的執行效率
阿新 • • 發佈:2019-01-31
本文對Python 2 和 Python 3 對集合-list進行迴圈時的執行效率進行比較
- 首先我定義了一個for_test函式,然後利用ipython的魔法函式 %timeit進行執行速度的測試
- %timeit會自動多次執行目標函式來獲得一個更準確的結果。
- 在測試的過程,發現一個比較奇怪的問題,如果不進行賦值操作的話,單單逐個獲取元素,並進行運算,Python 2 的效率高於 Python 3
- 如果加上一個賦值的操作,則Python 3 的效率高於 Python 2
- 但很奇怪的地方是如果我用 %time 來對函式進行一次測試,卻發現Python 2 的效率卻是高於 Python 3 的
用 %time 測試,只執行一次測試函式
def for_test(container):
for i, num in enumerate(container):
num = num/5*10 + 12 - 8
container[i] = num
container = list(range(1000000))
%time for_test(container)
- Python 2
Wall time: 126 ms # 多次執行的結果都是120-130 ms左右
Wall time: 129 ms
Wall time: 128 ms
- Python 3
Wall time: 191 ms # 多次執行均大於160ms,可以看出其效率低於Python 2
Wall time: 176 ms
Wall time: 183 ms
用 %timeit 測試,多次執行測試函式
def for_test(container):
for i, num in enumerate(container):
num = num/5*10 + 12 - 8
container[i] = num
container = list(range(1000000))
%timeit for_test(container)
- Python 2
10 loops, best of 3: 348 ms per loop # 可以發現相對於%time的測試結果顯著
- Python 3
176 ms ± 5.96 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
如果測試函式只進行運算而不進行重新賦值,則結果會發生變化
%time
def for_test(container):
for i, num in enumerate(container):
num = num/5*10 + 12 - 8
container = list(range(1000000))
%time for_test(container)
- Python 2
Wall time: 98 ms
Wall time: 96 ms
Wall time: 97 ms
Pyhton 3
Wall time: 142 ms
Wall time: 138 ms
Wall time: 175 ms
%timeit
def for_test(container):
for i, num in enumerate(container):
num = num/5*10 + 12 - 8
container = list(range(1000000))
%timeit for_test(container)
- Pyhton 2
10 loops, best of 3: 96.7 ms per loop
- Python 3
145 ms ± 4.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
總結
我的猜測是 %timeit 在Python 2 和 3 中的執行機制可能不同導致得到的結果不一樣