|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | +from contextlib import contextmanager |
| 8 | +from dataclasses import dataclass |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | + |
| 12 | +@dataclass |
| 13 | +class Measurement: |
| 14 | + metric: str |
| 15 | + value: float |
| 16 | + unit: str | None |
| 17 | + |
| 18 | + @classmethod |
| 19 | + def from_json_str(cls, s: str) -> "Measurement": |
| 20 | + data = json.loads(s.strip()) |
| 21 | + return cls(data["metric"], data["value"], data.get("unit")) |
| 22 | + |
| 23 | + def to_json_str(self) -> str: |
| 24 | + if self.unit is None: |
| 25 | + return json.dumps({"metric": self.metric, "value": self.value}) |
| 26 | + return json.dumps( |
| 27 | + {"metric": self.metric, "value": self.value, "unit": self.unit} |
| 28 | + ) |
| 29 | + |
| 30 | + |
| 31 | +@contextmanager |
| 32 | +def temporarily_move_outfile(outfile: Path): |
| 33 | + outfile_tmp = outfile.with_name(outfile.name + ".repeatedly_tmp") |
| 34 | + if outfile_tmp.exists(): |
| 35 | + raise Exception(f"{outfile_tmp} already exists") |
| 36 | + |
| 37 | + outfile.touch() |
| 38 | + outfile.rename(outfile_tmp) |
| 39 | + try: |
| 40 | + yield |
| 41 | + finally: |
| 42 | + outfile_tmp.rename(outfile) |
| 43 | + |
| 44 | + |
| 45 | +def read_measurements_from_outfile(outfile: Path) -> list[Measurement]: |
| 46 | + measurements = [] |
| 47 | + with open(outfile, "r") as f: |
| 48 | + for line in f: |
| 49 | + measurements.append(Measurement.from_json_str(line)) |
| 50 | + return measurements |
| 51 | + |
| 52 | + |
| 53 | +def write_measurements_to_outfile( |
| 54 | + outfile: Path, measurements: list[Measurement] |
| 55 | +) -> None: |
| 56 | + with open(outfile, "a") as f: |
| 57 | + for measurement in measurements: |
| 58 | + f.write(f"{measurement.to_json_str()}\n") |
| 59 | + |
| 60 | + |
| 61 | +def run_once(cmd: list[str], outfile: Path) -> list[Measurement]: |
| 62 | + with temporarily_move_outfile(outfile): |
| 63 | + proc = subprocess.run(cmd) |
| 64 | + if proc.returncode != 0: |
| 65 | + sys.exit(proc.returncode) |
| 66 | + |
| 67 | + return read_measurements_from_outfile(outfile) |
| 68 | + |
| 69 | + |
| 70 | +def sum_by_metric(measurements: list[Measurement]) -> dict[str, Measurement]: |
| 71 | + totals: dict[str, Measurement] = {} |
| 72 | + for measurement in measurements: |
| 73 | + if existing := totals.get(measurement.metric): |
| 74 | + measurement.value += existing.value |
| 75 | + totals[measurement.metric] = measurement |
| 76 | + return totals |
| 77 | + |
| 78 | + |
| 79 | +def repeatedly( |
| 80 | + cmd: list[str], |
| 81 | + iterations: int, |
| 82 | + outfile: Path, |
| 83 | + drop_highest: int = 0, |
| 84 | + drop_lowest: int = 0, |
| 85 | +) -> list[Measurement]: |
| 86 | + by_metric: dict[str, list[Measurement]] = {} |
| 87 | + |
| 88 | + for i in range(iterations): |
| 89 | + for metric, measurement in sum_by_metric(run_once(cmd, outfile)).items(): |
| 90 | + by_metric.setdefault(metric, []).append(measurement) |
| 91 | + |
| 92 | + if drop_highest + drop_lowest >= iterations: |
| 93 | + raise ValueError( |
| 94 | + f"drop_highest ({drop_highest}) + drop_lowest ({drop_lowest}) must be " |
| 95 | + f"less than the number of iterations ({iterations})" |
| 96 | + ) |
| 97 | + |
| 98 | + results = [] |
| 99 | + for metric, measurements in by_metric.items(): |
| 100 | + if drop_highest or drop_lowest: |
| 101 | + measurements.sort(key=lambda m: m.value) |
| 102 | + measurements = measurements[drop_lowest : len(measurements) - drop_highest] |
| 103 | + if not measurements: |
| 104 | + continue |
| 105 | + unit = measurements[0].unit |
| 106 | + value = sum(m.value for m in measurements) / len(measurements) |
| 107 | + results.append(Measurement(metric, value, unit)) |
| 108 | + |
| 109 | + return results |
| 110 | + |
| 111 | + |
| 112 | +class Args: |
| 113 | + iterations: int |
| 114 | + drop_highest: int |
| 115 | + drop_lowest: int |
| 116 | + outfile: Path |
| 117 | + cmd: str |
| 118 | + args: list[str] |
| 119 | + |
| 120 | + |
| 121 | +if __name__ == "__main__": |
| 122 | + parser = argparse.ArgumentParser( |
| 123 | + description="Repeatedly run a command, averaging the measurements it writes.", |
| 124 | + ) |
| 125 | + parser.add_argument( |
| 126 | + "-n", |
| 127 | + "--iterations", |
| 128 | + type=int, |
| 129 | + default=5, |
| 130 | + help="number of iterations", |
| 131 | + ) |
| 132 | + parser.add_argument( |
| 133 | + "-H", |
| 134 | + "--drop-highest", |
| 135 | + type=int, |
| 136 | + default=0, |
| 137 | + help="drop the n highest values of each metric before averaging", |
| 138 | + ) |
| 139 | + parser.add_argument( |
| 140 | + "-L", |
| 141 | + "--drop-lowest", |
| 142 | + type=int, |
| 143 | + default=0, |
| 144 | + help="drop the n lowest values of each metric before averaging", |
| 145 | + ) |
| 146 | + parser.add_argument( |
| 147 | + "-o", |
| 148 | + "--outfile", |
| 149 | + type=Path, |
| 150 | + default=Path("measurements.jsonl"), |
| 151 | + help="measurements file the command under test writes to", |
| 152 | + ) |
| 153 | + parser.add_argument( |
| 154 | + "cmd", |
| 155 | + help="command to repeatedly run", |
| 156 | + ) |
| 157 | + parser.add_argument( |
| 158 | + "args", |
| 159 | + nargs="*", |
| 160 | + default=[], |
| 161 | + help="arguments to pass to the command", |
| 162 | + ) |
| 163 | + args = parser.parse_args(namespace=Args()) |
| 164 | + |
| 165 | + measurements = repeatedly( |
| 166 | + [args.cmd] + args.args, |
| 167 | + args.iterations, |
| 168 | + args.outfile, |
| 169 | + args.drop_highest, |
| 170 | + args.drop_lowest, |
| 171 | + ) |
| 172 | + write_measurements_to_outfile(args.outfile, measurements) |
0 commit comments