Files
pp_122-mko-lab2/lec3/gil_demo.py
T
2026-11-14 10:09:26 +03:00

42 lines
1.3 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Одна CPU-нагрузка последовательно и в ThreadPoolExecutor."""
import sys
import time
from concurrent.futures import ThreadPoolExecutor
def busy_sum(n):
"""Чистый Python: нагрузка на CPU без ожидания ввода-вывода."""
total = 0
for i in range(n):
total += i * i
return total
def serial(n, workers):
return sum(busy_sum(n) for _ in range(workers))
def threaded(pool, n, workers):
return sum(pool.map(busy_sum, [n] * workers))
def measure(function, *args):
function(*args) # прогрев: запуск workers и прогрев кэшей
start = time.perf_counter()
result = function(*args)
return result, time.perf_counter() - start
if __name__ == "__main__":
n, workers = 500_000, 4
gil = getattr(sys, "_is_gil_enabled", lambda: True)()
expected, serial_time = measure(serial, n, workers)
with ThreadPoolExecutor(max_workers=workers) as pool:
actual, thread_time = measure(threaded, pool, n, workers)
print(f"GIL включён: {gil}")
print(f"Последовательно: {serial_time:.4f} с")
print(f"Потоки: {thread_time:.4f} с")
print(f"Результаты совпали: {actual == expected}")
assert actual == expected