示例工程 19-threading-gil-multiprocessing
19-threading-gil-multiprocessing/06-threadpool-io/threadpool_io.py
"""演示用 ThreadPoolExecutor 限制并发度并加速 IO。"""
from __future__ import annotations
import time
from concurrent.futures import ThreadPoolExecutor
TASKS = 8
WORKERS = 4
DELAY = 0.02
def io_task(index: int, delay: float = DELAY) -> int:
time.sleep(delay)
return index
def bounded(tasks: int = TASKS, workers: int = WORKERS) -> tuple[list[int], float]:
started = time.perf_counter()
with ThreadPoolExecutor(max_workers=workers) as pool:
results = list(pool.map(io_task, range(tasks)))
return results, time.perf_counter() - started
def serial(tasks: int = TASKS) -> tuple[list[int], float]:
started = time.perf_counter()
results = [io_task(index) for index in range(tasks)]
return results, time.perf_counter() - started
def main() -> None:
bounded_results, bounded_time = bounded()
serial_results, serial_time = serial()
print(f"bounded: {bounded_results} {bounded_time:.2f}s")
print(f"serial: {serial_results} {serial_time:.2f}s")
print(f"speedup: {serial_time / bounded_time:.1f}x")
if __name__ == "__main__":
main()