计算密集型的多线程真的提速了。
(test314) PS Z:\py> python3.14t.exe .\ng.py
two-thread(noGIL) 耗时 1.45s 结果 170666663466666680000000
(test314) PS Z:\py> python3.14.exe .\ng.py
two-thread(noGIL) 耗时 3.05s 结果 170666663466666680000000
# 需要 Python 3.14 free-threaded 构建(configure --disable-gil)
import threading
import time
N = 80_000_000 # 任务总量
half = N // 2
results = [0, 0] # 两个线程写不同槽,无锁
def partial_sum(start, end, idx):
"""计算 [start, end) 的平方和"""
s = 0
for i in range(start, end):
s += i * i
results[idx] = s
def run_two_threads():
t1 = threading.Thread(target=partial_sum, args=(0, half, 0))
t2 = threading.Thread(target=partial_sum, args=(half, N, 1))
ta = time.perf_counter()
t1.start(); t2.start()
t1.join(); t2.join()
tb = time.perf_counter()
total = results[0] + results[1]
print(f"two-thread(noGIL) 耗时 {tb-ta:.2f}s 结果 {total}")
if __name__ == "__main__":
run_two_threads()
--
FROM 171.221.52.*