"""Median time and working memory per (input, algorithm) from `sa bench` lines.

Line format: algo kind n seconds peak_rss_kb base_rss_kb checksum
base_rss is measured after the text (n bytes) and SA (4n bytes) are touched,
so (peak - base) is the working space of the construction itself.
All algorithms on the same input must produce the same checksum.
"""
import collections
import statistics
import sys

rows = collections.defaultdict(list)
sums = collections.defaultdict(set)
order_k, order_a = [], []
for line in open(sys.argv[1]):
    algo, kind, n, sec, peak, base, h = line.split()
    rows[kind, algo].append((float(sec), int(peak), int(base), int(n)))
    sums[kind].add(h)
    if kind not in order_k:
        order_k.append(kind)
    if algo not in order_a:
        order_a.append(algo)

for kind in order_k:
    if len(sums[kind]) != 1:
        sys.exit(f"checksum mismatch on {kind}: {sums[kind]}")

print(f"{'input':6} {'algorithm':11} {'runs':>4} {'median_s':>9} {'min_s':>7} {'max_s':>7} {'work_B/char':>11} {'peak_B/char':>11}")
for kind in order_k:
    for algo in order_a:
        r = rows[kind, algo]
        n = r[0][3]
        t = [x[0] for x in r]
        work = statistics.median((x[1] - x[2]) * 1024 / n for x in r)
        peak = statistics.median(x[1] * 1024 / n for x in r)
        print(f"{kind:6} {algo:11} {len(r):4d} {statistics.median(t):9.3f} {min(t):7.3f} {max(t):7.3f} {work:11.2f} {peak:11.2f}")
print("checksums identical across algorithms for every input")
