线程数增加,差距继续拉大。
(test314) PS Z:\py> python3.14t.exe .\ng.py 5
5 线程(noGIL) 耗时 0.6
4s 结果 170666663466666680000000
(test314) PS Z:\py> python3.14t.exe .\ng.py 10
10 线程(noGIL) 耗时 0.41s 结果 170666663466666680000000
(test314) PS Z:\py> python3.14t.exe .\ng.py 15
15 线程(noGIL) 耗时 0.34s 结果 170666663466666680000000
有GIL的版本
(test314) PS Z:\py> python3.14.exe .\ng.py 15
15 线程(noGIL) 耗时 2.78s 结果 170666663466666680000000
# 需要 Python 3.14 free-threaded
"""
ng.py [M]
在 Python 3.14 free-threaded(--disable-gil)下,
用 M 个线程并行计算 0…N-1 的平方和。
M 省略时默认=CPU 核数;若给出,则必须是 1<=M<500 的正整数。
"""
import os, sys, threading, time
from concurrent.futures import ThreadPoolExecutor
N = 80_000_000 # 任务总量
DEFAULT_M = os.cpu_count()
def partial_sum(start: int, end: int) -> int:
s = 0
for i in range(start, end):
s += i * i
return s
def parse_workers() -> int:
if len(sys.argv) == 1:
return DEFAULT_M
try:
m = int(sys.argv[1])
if 1 <= m < 500:
return m
raise ValueError
except ValueError:
print("用法: python3.14t ng.py [M]\n"
"可选参数 M 必须是 1 到 499 之间的整数", file=sys.stderr)
sys.exit(1)
def run(workers: int) -> int:
chunk = N // workers
ranges = [(i * chunk, (i + 1) * chunk if i != workers - 1 else N)
for i in range(workers)]
ta = time.perf_counter()
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = [pool.submit(partial_sum, st, ed) for st, ed in ranges]
total = sum(f.result() for f in futures)
tb = time.perf_counter()
print(f"{workers} 线程(noGIL) 耗时 {tb-ta:.2f}s 结果 {total}")
return total
if __name__ == "__main__":
run(parse_workers())
※ 修改:·poocp 于 Oct 20 06:11:00 2025 修改本文·[FROM: 171.221.52.*]
※ 来源:·水木社区
http://www.mysmth.net·[FROM: 171.221.52.*]
修改:poocp FROM 171.221.52.*
FROM 171.221.52.*