"""对比 IO 等待在串行与多线程下的耗时。""" from __future__ import annotations import threading import time TASKS = 4 DELAY = 0.05 def io_task(delay: float = DELAY) -> str: time.sleep(delay) return "done" def serial(tasks: int = TASKS) -> tuple[list[str], float]: started = time.perf_counter() results = [io_task() for _ in range(tasks)] return results, time.perf_counter() - started def threaded(tasks: int = TASKS) -> tuple[list[str], float]: results = [""] * tasks def worker(index: int) -> None: results[index] = io_task() 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: serial_results, serial_time = serial() threaded_results, threaded_time = threaded() print(f"serial: {serial_results} {serial_time:.2f}s") print(f"threaded: {threaded_results} {threaded_time:.2f}s") print(f"speedup: {serial_time / threaded_time:.1f}x") if __name__ == "__main__": main()