#!/usr/bin/env python3
"""Does a sibling CPU burner remove the idle-wake penalty? (no GIL interference)"""
import json, os, subprocess, time, statistics, sys

REC = "/Users/oscar/.worktree/hot-reload/labs/hot-reload/target/kan-hot/debug/rustc"
ROOT = "/Users/oscar/.worktree/hot-reload/labs/hot-reload"
SRC = os.path.join(ROOT, "api-common/src/lib.rs")
orig = open(SRC).read()
inv = json.load(open(os.path.join(REC, "api_common.json")))
burners = []


def compile_():
    open(SRC, "w").write(orig.replace("nested-v1", f"x-{time.time_ns()}"))
    time.sleep(0.15)
    started = time.monotonic()
    p = subprocess.run(inv["argv"], cwd=inv["cwd"], env=dict(inv["env"]),
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    elapsed = (time.monotonic() - started) * 1000
    assert p.returncode == 0
    return elapsed


def burn(count, nice=None):
    stop()
    for _ in range(count):
        cmd = ["yes"] if nice is None else ["nice", "-n", str(nice), "yes"]
        burners.append(subprocess.Popen(cmd, stdout=subprocess.DEVNULL,
                                        stderr=subprocess.DEVNULL))


def stop():
    while burners:
        p = burners.pop()
        p.kill()
        p.wait()


try:
    for label, count, nice in (("no burner", 0, None), ("1 burner", 1, None),
                               ("1 burner nice+20", 1, 20), ("6 burners", 6, None)):
        burn(count, nice)
        times = [compile_() for _ in range(6)]
        print(f"{label:20s} median={statistics.median(times):6.1f} mean={statistics.mean(times):6.1f} "
              f"min={min(times):6.1f} max={max(times):6.1f}")
finally:
    stop()
    open(SRC, "w").write(orig)
