示例工程 21-free-threading-concurrency-choice
21-free-threading-concurrency-choice/02-free-threaded-bench/free_threaded_bench.py
"""free-threaded 构建下的多线程 CPU 基准;GIL 版直接跳过。"""
from __future__ import annotations
import sys
import sysconfig
import threading
import time
TASKS = 2
LIMIT = 300_000
def is_free_threaded() -> bool:
return bool(sysconfig.get_config_var("Py_GIL_DISABLED")) or not bool(
getattr(sys, "_is_gil_enabled", lambda: True)()
)
def burn(limit: int = LIMIT) -> int:
total = 0
for value in range(limit):
total += value
return total
def bench(tasks: int = TASKS) -> tuple[list[int], float]:
results = [0] * tasks
def worker(index: int) -> None:
results[index] = burn()
started = time.perf_counter()
threads = [threading.Thread(target=worker, args=(index,)) for index in range(tasks)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return results, time.perf_counter() - started
def main() -> None:
if not is_free_threaded():
print("free-threaded build: no")
print("skip: install 3.13t/3.14t (uv python install 3.14t) and run with PYTHON_GIL=0")
return
results, elapsed = bench()
print("free-threaded build: yes")
print(f"results: {results[0]}")
print(f"threads_2x: {elapsed:.2f}s")
if __name__ == "__main__":
main()