#!/usr/bin/env python3

import statistics
import subprocess
import sys
import time
from pathlib import Path


def warn_if_benchmark_environment_is_noisy() -> None:
    governor_path = Path("/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor")
    if governor_path.exists():
        governor = governor_path.read_text(encoding="utf-8").strip()
        if governor != "performance":
            print(
                f"warning: cpu2 scaling governor is '{governor}', expected 'performance'",
                file=sys.stderr,
            )

    randomize_va_space = Path("/proc/sys/kernel/randomize_va_space")
    if randomize_va_space.exists():
        value = randomize_va_space.read_text(encoding="utf-8").strip()
        if value != "0":
            print(
                f"warning: kernel.randomize_va_space is '{value}', expected '0'",
                file=sys.stderr,
            )


def main() -> int:
    runs = int(sys.argv[1]) if len(sys.argv) > 1 else 1
    rom = Path.home() / "Games" / "flappyboy.gb"
    warn_if_benchmark_environment_is_noisy()
    times = []
    for _ in range(runs):
        start = time.perf_counter_ns()
        subprocess.run(
            [
                "taskset",
                "-c",
                "2",
                "./tlmboy",
                "-r",
                rom,
                "--fps-cap=-1",
                "--max-cycles=15000000",
            ],
            check=True,
        )
        times.append(time.perf_counter_ns() - start)

    for i in range(len(times)):
        times[i] /= 1e6

    print()
    print(f"median: {statistics.median(times)} ms")
    print(f"lowest: {min(times)} ms")
    print(f"highest: {max(times)} ms")
    return 0


raise SystemExit(main())

