示例工程 19-threading-gil-multiprocessing

19-threading-gil-multiprocessing/01-cpu-bound-threads/cpu_bound_threads.py

python · 1.2 KB

"""对比 CPU 密集任务在串行与多线程下的耗时(GIL 限制)。"""
 
from __future__ import annotations
 
import threading
import time
 
TASKS = 4
LIMIT = 1_000_000
 
 
def burn(limit: int = LIMIT) -> int:
    total = 0
    for value in range(limit):
        total += value
    return total
 
 
def serial(tasks: int = TASKS) -> tuple[list[int], float]:
    started = time.perf_counter()
    results = [burn() for _ in range(tasks)]
    return results, time.perf_counter() - started
 
 
def threaded(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:
    serial_results, serial_time = serial()
    threaded_results, threaded_time = threaded()
    print(f"serial: {serial_results[0]} {serial_time:.2f}s")
    print(f"threaded: {threaded_results[0]} {threaded_time:.2f}s")
    print(f"speedup: {serial_time / threaded_time:.2f}x")
 
 
if __name__ == "__main__":
    main()