示例工程 19-threading-gil-multiprocessing

19-threading-gil-multiprocessing/04-process-pool/process_pool.py

python · 1.1 KB

"""演示 CPU 密集任务用进程池绕过 GIL。"""
 
from __future__ import annotations
 
import time
from concurrent.futures import ProcessPoolExecutor
 
TASKS = 4
LIMIT = 1_000_000
 
 
def cpu_work(limit: int = LIMIT) -> int:
    return sum(value * value for value in range(limit))
 
 
def serial(tasks: int = TASKS) -> tuple[list[int], float]:
    started = time.perf_counter()
    results = [cpu_work() for _ in range(tasks)]
    return results, time.perf_counter() - started
 
 
def pooled(tasks: int = TASKS, workers: int = 2) -> tuple[list[int], float]:
    started = time.perf_counter()
    with ProcessPoolExecutor(max_workers=workers) as pool:
        results = list(pool.map(cpu_work, [LIMIT] * tasks))
    return results, time.perf_counter() - started
 
 
def main() -> None:
    serial_results, serial_time = serial()
    pooled_results, pooled_time = pooled()
    print(f"serial: {serial_results[0]} {serial_time:.2f}s")
    print(f"pooled: {pooled_results[0]} {pooled_time:.2f}s")
    print(f"same: {serial_results == pooled_results}")
 
 
if __name__ == "__main__":
    main()