眾所周知,Python 3.11 版本帶來了較大的性能提升,但是,它具體在哪些方面上得到了優化呢?除了著名的“香農計劃”外,它還包含哪些與性能相關的優化呢?本文將帶你一探究竟!
作者:Beshr Kayali
譯者:豌豆花下貓@Python貓
英文:https://log.beshr.com/python-311-speedup-part-1
轉載請保留作者及譯者資訊!
Python 3.11 在幾天前發布了,它照例帶來了很多新特性,例如例外組、細粒度的錯誤位置與堆疊回溯、標準庫對 TOML 的決議支持,當然,還有備受大家期待的由 faster CPython 專案帶來的速度提升,
根據 pyperformance 的基準測驗,CPython 3.11 比 CPython 3.10 平均快 25%,這項改進的原因之一是 Guido 命名的“香農計劃”(即 faster CPython),對于 3.11 版本,這個計劃在兩個主要方向進行了大量優化:啟動時和運行時,
除此之外,Python 3.11 還包含有其它的優化,這些優化不屬于香農計劃,
在本文中,我將詳細介紹 3.11.0 穩定版中常規優化的細節(即非 faster CPython 專案的改進),
(譯注:作者表示將另寫一篇文章介紹 faster CPython 的改進細節,屆時,我也將繼續翻譯,敬請期待!)
目錄
- 優化了一些 printf 風格 % 的格式化代碼
- 優化了 Python 大整數的除法
- 優化了數字 PyLongs 求和
- 精簡串列的擴容操作,提升了 list.append 性能
- 減少了全 unicode 鍵的字典的記憶體占用
- 提升了使用asyncio.DatagramProtocol 傳輸大檔案的速度
- 對于 math 庫:優化了 comb(n, k) 與 perm(n, k=None)
- 對于 statistics 庫:優化了 mean(data)、variance(data, xbar=None) 與 stdev(data, xbar=None)
- 純 ASCII 字串的 unicodedata.normalize(),提升到常數時間
優化了一些 printf 風格 % 的格式化代碼
使用格式化的字串字面量(formatted string literals)是最快的格式化字串的方法,
Python 3.10 中的一個簡單基準測驗:
$ python -m pyperf timeit -s \
'k = "foo"; v = "bar"' -- '"%s = %r" % (k, v)'
.....................
Mean +- std dev: 187 ns +- 8 ns
但是使用 f-string 似乎要快 42%:
$ python -m pyperf timeit -s \
'k = "foo"; v = "bar"' -- 'f"{k!s} = {v!r}"'
.....................
Mean +- std dev: 131 ns +- 9 ns
優化性能的手段是將簡單的 C 風格的格式化方法轉換為 f-string 方法,在 3.11.0 中,只轉換了 %s、%r 和 %a 三種,但是目前有一個待合入的 pull request,將會支持:%d、%i、%u、%o、%x、%X、%f、 %e、%g、%F、%E、%G,
例如,下面是 Python 3.11 中相同基準測驗的結果:
$ python -m pyperf timeit -s \
'k = "foo"; v = "bar"' -- '"%s = %r" % (k, v)'
.....................
Mean +- std dev: 100 ns +- 5 ns
大約快了 87%!當然,3.11 中其它的優化對此也有影響,比如更快的解釋器啟動時間,
優化了 Python 大整數的除法
在 Python 3.10 中:
python -m pyperf timeit -s 'x=10**1000' -- 'x//10'
.....................
Mean +- std dev: 1.18 us +- 0.02 us
在 Python 3.11 中:
python -m pyperf timeit -s 'x=10**1000' -- 'x//10'
.....................
Mean +- std dev: 995 ns +- 15 ns
大約快了18%,
這項優化源自 Mark Dickinson 的一個發現,即編譯器總會生成 128:64 的除法指令,盡管處理的是 30 位的數值,
即使在 x64 上,Python 的除法也有些殘缺,假設是 30 位數字,則多精度除法所需的基本結構是 64 位除以 32 位的無符號整數除法,產生一個 32 位的商(理想情況下還會產生一個 32 位余數),有一個 x86/x64 指令可以做到這一點,也就是 DIVL,但是如果不使用行內匯編,當前版本的 GCC 和 Clang 顯然做不到從 longobject.c 中發出該指令——它們只會在 x64 上使用 DIVQ(128 位除以 64 位的除法,盡管被除數的前 64 位被設為零),而在 x86 上則使用固有的 __udivti3 或 __udivti4,
——Mark Dickinson(全文)
優化了數字 PyLongs 求和
這里有一個 issue,它發現 Python 2.7 中 sum 的速度比 Python 3 快得多,不幸的是,在某些條件下,3.11.0 似乎仍然如此,
Python 2.7:
$ python -m pyperf timeit -s 'd = [0] * 10000' -- 'sum(d)'
.....................
Mean +- std dev: 37.4 us +- 1.1 us
Python 3.10:
$ python -m pyperf timeit -s 'd = [0] * 10000' -- 'sum(d)'
.....................
Mean +- std dev: 52.7 us +- 1.3 us
Python 3.11:
$ python -m pyperf timeit -s 'd = [0] * 10000' -- 'sum(d)'
.....................
Mean +- std dev: 39.0 us +- 1.0 us
Python3.10 和 3.11 之間的區別在于,通過在 sum 函式的快速加法分支中行內對單個數字 PyLongs 的解包,可以提升在單個數字 PyLongs 上呼叫 sum 的性能,這樣做可以避免在解包時呼叫 PyLong_AsLongAndOverflow,
值得注意的是,在某些情況下,Python 3.11 在整數求和時仍然明顯慢于 Python 2.7,我們希望在 Python 中通過實作更高效的整數,獲得更多的改進,
精簡串列的擴容操作,提升了 list.append 性能
在 Python 3.11 中,list.append 有了顯著的性能提升(大約快 54%),
Python 3.10 的串列 append:
$ python -m pyperf timeit -s \
'x = list(map(float, range(10_000)))' -- '[x.append(i) for i in range(10_000)]'
.....................
Mean +- std dev: 605 us +- 20 us
Python 3.11 的串列 append:
$ python -m pyperf timeit -s \
'x = list(map(float, range(10_000)))' -- '[x.append(i) for i in range(10_000)]'
.....................
Mean +- std dev: 392 us +- 14 us
對于簡單的串列推導式,也有一些小的改進:
Python 3.10:
$ python -m pyperf timeit -s \
'' -- '[x for x in list(map(float, range(10_000)))]'
.....................
Mean +- std dev: 553 us +- 19 us
Python 3.11:
$ python -m pyperf timeit -s \
'' -- '[x for x in list(map(float, range(10_000)))]'
.....................
Mean +- std dev: 516 us +- 16 us
譯注:記得在 3.9 版本的時候,Python 優化了呼叫 list()、dict() 和 range() 等內置型別的速度,在不起眼處,竟還能持續優化!
減少了全 unicode 鍵的字典的記憶體占用
這項優化令 Python 在使用全為 Unicode 鍵的字典時,快取的效率更高,這是因為使用的記憶體減少了,那些 Unicode 鍵的哈希會被丟棄,因為那些 Unicode 物件已經有哈希了,
例如,在 64 位平臺上,Python 3.10 運行結果:
>>> sys.getsizeof(dict(foo="bar", bar="foo"))
232
在 Python 3.11 中:
>>> sys.getsizeof(dict(foo="bar", bar="foo"))
184
(譯注:插個題外話,Python 的 getsizeof 是一種“淺計算”,這篇《Python在計算記憶體時應該注意的問題?》區分了“深淺計算”,可以讓你對 Python 計算記憶體有更深的理解,)
提升了使用asyncio.DatagramProtocol 傳輸大檔案的速度
asyncio.DatagramProtocol 提供了一個用于實作資料報(UDP)協議的基類,有了這個優化,使用asyncio UDP 傳輸大檔案(比如 60 MiB)將比 Python 3.10 快 100 多倍,
這是通過計算一次緩沖區的大小并將其存盤在一個屬性中來實作的,這使得通過 UDP 傳輸大檔案時,asyncio.DatagramProtocol 有著數量級的提速,
PR msoxzw 的作者提供了以下的 測驗腳本,
對于 math 庫:優化了 comb(n, k) 與 perm(n, k=None)
Python 3.8 在math 標準庫中增加了 comb(n, k) 和 perm(n, k=None) 函式,兩者都用于計算從 n 個無重復的元素中選擇 k 個元素的方法數,comb 回傳無序計算的結果,而perm 回傳有序計算的結果,(譯注:即一個求組合數,一個求排列數)
3.11 的優化由多個較小的改進組成,比如使用分治演算法來實作 Karatsuba 大數乘法,以及盡可能用 C 語言unsigned long long 型別而不是 Python 整數進行comb計算(*),
另外一項改進是針對較小的 k 值(0 <= k <= n <= 67):
(譯注:以下兩段費解,暫跳過)
對于
0 <= k <= n <= 67,comb(n, k)always fits into auint64_t. We compute it ascomb_odd_part << shiftwhere2 ** shiftis the largest power of two dividingcomb(n, k)andcomb_odd_partiscomb(n, k) >> shift.comb_odd_partcan be calculated efficiently via arithmetic modulo2 ** 64, using three lookups and twouint64_tmultiplications, while the necessary shift can be computed via Kummer's theorem: it's the number of carries when addingkton - kin binary, which in turn is the number of set bits ofn ^ k ^ (n - k). *
One more improvement is that the previous popcount-based code for computing the largest power of two dividing math.comb(n, k) (for small n) got replaced with a more direct method based on counting trailing zeros of the factorials involved. (*).
Python 3.10:
$ python -m pyperf timeit -s \
'import math' -- 'math.comb(100, 55)'
.....................
Mean +- std dev: 3.72 us +- 0.07 us
# ---
$ python -m pyperf timeit -s \
'import math' -- 'math.comb(10000, 5500)'
.....................
Mean +- std dev: 11.9 ms +- 0.1 ms
Python 3.11:
$ python -m pyperf timeit -s \
'import math' -- 'math.comb(100, 55)'
.....................
Mean +- std dev: 476 ns +- 20 ns
# ---
$ python -m pyperf timeit -s \
'import math' -- 'math.comb(10000, 5500)'
.....................
Mean +- std dev: 2.28 ms +- 0.10 ms
對于 statistics 庫:優化了 mean(data)、variance(data, xbar=None) 與 stdev(data, xbar=None)
3.11 優化了statistics模塊中的 mean、variance與stdev 函式,如果入參是一個迭代器,則會直接用于計算,而不是先將其轉換為串列,這種計算方法 的速度比之前的快了一倍,*
Python 3.10:
# Mean
$ python -m pyperf timeit -s \
'import statistics' -- 'statistics.mean(range(1_000))'
.....................
Mean +- std dev: 255 us +- 11 us
# Variance
$ python -m pyperf timeit -s \
'import statistics' -- 'statistics.variance((x * 0.1 for x in range(0, 10)))'
.....................
Mean +- std dev: 77.0 us +- 2.9 us
# Sample standard deviation (stdev)
$ python -m pyperf timeit -s \
'import statistics' -- 'statistics.stdev((x * 0.1 for x in range(0, 10)))'
.....................
Mean +- std dev: 78.0 us +- 2.2 us
Python 3.11:
# Mean
$ python -m pyperf timeit -s \
'import statistics' -- 'statistics.mean(range(1_000))'
.....................
Mean +- std dev: 193 us +- 7 us
# Variance
$ python -m pyperf timeit -s \
'import statistics' -- 'statistics.variance((x * 0.1 for x in range(0, 10)))'
.....................
Mean +- std dev: 56.1 us +- 2.3 us
# Sample standard deviation (stdev)
$ python -m pyperf timeit -s \
'import statistics' -- 'statistics.stdev((x * 0.1 for x in range(0, 10)))'
.....................
Mean +- std dev: 59.4 us +- 2.6 us
純 ASCII 字串的 unicodedata.normalize(),提升到常數時間
對于 unicodedata.normalize() 方法,如果提供的入參是純 ASCII 字串,則通過 unicode 快速檢查演算法 迅速回傳結果,這項檢查使用的是PyUnicode_IS_ASCII 實作,
Python 3.10:
$ python -m pyperf timeit -s \
'import unicodedata' -- 'unicodedata.normalize("NFC", "python")'
.....................
Mean +- std dev: 83.3 ns +- 4.3 ns
Python 3.11:
$ python -m pyperf timeit -s \
'import unicodedata' -- 'unicodedata.normalize("NFC", "python")'
.....................
Mean +- std dev: 34.2 ns +- 1.2 ns
最后的話:
- 我寫這篇文章是為了加深自己對 Python 3.11 最新成果的認識,如果內容有錯,請通過email 或者 Twitter告訴我,(譯注:本翻譯是出于促進自己學習及加強理解的目的,若有錯漏,歡迎指正!)
- 附 HackerNews 上的評論
- 在下一篇文章中,我將分析 faster CPython 專案帶來的優化點,敬請期待!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/531896.html
標籤:Python
下一篇:每日演算法題之撲克牌順子
