add lec1,lec2,lec3,lec4

This commit is contained in:
2026-11-14 10:09:26 +03:00
commit a64a74f1d5
23 changed files with 398 additions and 0 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
+12
View File
@@ -0,0 +1,12 @@
import statistics
import time
def bench(func, *args, repeats=5, warmup=1):
"""Запускает func(*args) несколько раз и возвращает медиану и разброс, с."""
for _ in range(warmup): # прогрев: кэши, JIT, запуск пула
func(*args)
times = []
for _ in range(repeats):
start = time.perf_counter() # монотонный таймер высокого разрешения
func(*args)
times.append(time.perf_counter() - start)
return statistics.median(times), min(times), max(times)
Executable
+12
View File
@@ -0,0 +1,12 @@
import random
def count_hits(n_points, seed):
"""Сколько случайных точек из квадрата [0,1]x[0,1] попало в четверть круга."""
rng = random.Random(seed) # свой генератор у каждой порции
hits = 0
for _ in range(n_points):
x, y = rng.random(), rng.random()
if x * x + y * y <= 1.0:
hits += 1
return hits
def estimate_pi_serial(n_points):
return 4 * count_hits(n_points, seed=0) / n_points
+10
View File
@@ -0,0 +1,10 @@
from concurrent.futures import ProcessPoolExecutor
from mc import count_hits
def estimate_pi_parallel(n_points, pool, n_workers):
"""Делит работу на n_workers порций и считает их в пуле процессов."""
chunk = n_points // n_workers
sizes = [chunk] * n_workers
sizes[-1] += n_points - chunk * n_workers # остаток — последней порции
seeds = range(1, n_workers + 1) # разные зёрна у порций
hits = sum(pool.map(count_hits, sizes, seeds))
return 4 * hits / n_points
+14
View File
@@ -0,0 +1,14 @@
from concurrent.futures import ProcessPoolExecutor
from bench import bench
from mc import estimate_pi_serial
from mc_parallel import estimate_pi_parallel
N = 20_000_000
if __name__ == "__main__":
t1, _, _ = bench(estimate_pi_serial, N)
print(f"Последовательно: T(1) = {t1:.2f} с")
print(" p T(p), с S(p) E(p)")
for p in [1, 2, 4, 6, 8, 10]:
with ProcessPoolExecutor(max_workers=p) as pool:
tp, _, _ = bench(estimate_pi_parallel, N, pool, p)
s = t1 / tp
print(f"{p:2d} {tp:8.2f} {s:5.2f} {s / p:5.2f}")
+13
View File
@@ -0,0 +1,13 @@
from concurrent.futures import ProcessPoolExecutor
from bench import bench
from mc_parallel import estimate_pi_parallel
N_PER_WORKER = 5_000_000 # объём работы на одного исполнителя
if __name__ == "__main__":
print(" p N T(p), с E_weak")
for p in [1, 2, 4, 6, 8, 10]:
n = N_PER_WORKER * p # задача растёт вместе с числом процессов
with ProcessPoolExecutor(max_workers=p) as pool:
tp, _, _ = bench(estimate_pi_parallel, n, pool, p)
if p == 1:
t_base = tp
print(f"{p:2d} {n:10_d} {tp:7.2f} {t_base / tp:6.2f}")