シェルスクリプトマガジン

レポート2(Vol.98掲載)

著者:末安 泰三

Pythonソフトウエア財団が2025年10月1日にリリース予定のPython 3.14では、性能向上の足かせだった大域ロック(GIL)を無効化できる。それにより、マルチスレッド処理を大幅に高速化可能だ。マルチスレッド処理のコードを使って、実際にどの程度高速化するのかを検証する。

シェルスクリプトマガジン Vol.98は以下のリンク先でご購入できます。

図1 検証に使用したPythonコード

import time, threading

N = 100000000
data = list(range(N))
def work(a, b): return sum(x*x for x in data[a:b])
def bench(threads=4):
  # シングルスレッド
  t=time.perf_counter()
  print("single:", work(0,N), 
        "in", time.perf_counter()-t)
  # マルチスレッド
  step=N//threads; res=[0]*threads; th=[]
  t=time.perf_counter()
  for i in range(threads):
    a=i*step; b=N if i==threads-1 else a+step
    th.append(
      threading.Thread(target=lambda j=i: \
                       res.__setitem__(j, work(a,b)))
    )
    th[-1].start()
  [x.join() for x in th]
  print(f"{threads} threads:", sum(res), 
        "in", time.perf_counter()-t)
bench()