Files
mtusi2026lab5/scripts/summarize.py
T

44 lines
3.5 KiB
Python
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.
"""Таблица отчёта из JSON; без ручного переноса значений."""
import csv
import json
from pathlib import Path
import re
ROOT = Path(__file__).resolve().parents[1]
load = json.loads((ROOT / 'evidence/load-pipeline.json').read_text(encoding='utf-8'))
faults = json.loads((ROOT / 'evidence/pipeline.json').read_text(encoding='utf-8'))
text = ['| Профиль | Bytes/image | Завершено за 3 повтора | Успешных image/s (min–max) | p50 ready, s | p95 ready, s | p99 ready, s | Ошибки |',
'| --- | --- | --- | --- | --- | --- | --- | --- |']
for profile in sorted({r['profile'] for r in load}):
rows = [r for r in load if r['profile'] == profile]
def span(key):
return f"{min(r[key] for r in rows):.3f}–{max(r[key] for r in rows):.3f}"
text.append(f"| {profile} | {rows[0]['bytes_per_image']} | {sum(r['completed'] for r in rows)} | {span('successful_rps')} | {span('p50')} | {span('p95')} | {span('p99')} | {sum(len(r['failures']) for r in rows)} |")
def mib(value):
number, unit = re.match(r'([0-9.]+)([A-Za-z]+)', value.strip()).groups()
return float(number) * {'B':1/1048576,'KiB':1/1024,'MiB':1,'GiB':1024,'kB':1000/1048576,'MB':1000000/1048576,'GB':1000000000/1048576}[unit]
snapshots = [s for r in load for s in r['stats']]
peak_cpu = max(sum(float(c['CPUPerc'].strip('%')) for c in s['containers']) for s in snapshots)
peak_memory = max(sum(mib(c['MemUsage'].split('/')[0]) for c in s['containers']) for s in snapshots)
text.extend(['', f'В собранных snapshots максимальная сумма CPU контейнеров: **{peak_cpu:.1f}%** (100% = один CPU); сумма cgroup memory: **{peak_memory:.1f} MiB**. Это максимум редких снимков, не непрерывно измеренный пик.', ''])
points = ('before_publish','after_publish','before_effect','after_original','after_variants','after_commit')
text.extend(['| Точка crash | Повторов | Полная длительность сценария, s (min–max) |', '| --- | --- | --- |'])
for point in points:
rows = [r for r in faults if r['scenario'] == point]
text.append(f"| {point} | {len(rows)} | {min(r['seconds'] for r in rows):.3f}–{max(r['seconds'] for r in rows):.3f} |")
text.extend(['', 'Во всех сохранённых crash/version/replay-сценариях проверки инвариантов прошли. Увеличение входного изображения снижает throughput и повышает время до ready в измеренном профиле. Повторы показывают разброс, а не статистически надёжную оценку хвостов: выборка и длительность малы.'])
path = ROOT / 'REPORT.md'
report = path.read_text(encoding='utf-8')
begin, end = '<!-- MEASUREMENTS BEGIN -->', '<!-- MEASUREMENTS END -->'
block = begin + '\n\n' + '\n'.join(text) + '\n\n' + end
if begin in report:
report = report[:report.index(begin)] + block + report[report.index(end)+len(end):]
else:
report = report.replace('<!-- MEASUREMENTS -->', block)
path.write_text(report, encoding='utf-8')
with (ROOT / 'evidence/measurements.csv').open('w', newline='', encoding='utf-8') as target:
writer = csv.DictWriter(target, fieldnames=['profile','repeat','completed','successful_rps','p50','p95','p99','error_fraction'])
writer.writeheader()
writer.writerows({key:row[key] for key in writer.fieldnames} for row in load)
print('\n'.join(text))