|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +import os |
| 6 | +import resource |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +import tempfile |
| 10 | +from dataclasses import dataclass |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | +OUTFILE = Path() / "measurements.jsonl" |
| 14 | + |
| 15 | + |
| 16 | +@dataclass |
| 17 | +class PerfMetric: |
| 18 | + event: str |
| 19 | + factor: float = 1 |
| 20 | + unit: str | None = None |
| 21 | + |
| 22 | + |
| 23 | +@dataclass |
| 24 | +class RusageMetric: |
| 25 | + name: str |
| 26 | + factor: float = 1 |
| 27 | + unit: str | None = None |
| 28 | + |
| 29 | + |
| 30 | +PERF_METRICS = { |
| 31 | + "task-clock": PerfMetric("task-clock", factor=1e-9, unit="s"), |
| 32 | + "wall-clock": PerfMetric("duration_time", factor=1e-9, unit="s"), |
| 33 | + "instructions": PerfMetric("instructions"), |
| 34 | +} |
| 35 | + |
| 36 | +PERF_UNITS = { |
| 37 | + "msec": 1e-3, |
| 38 | + "ns": 1e-9, |
| 39 | +} |
| 40 | + |
| 41 | +RUSAGE_METRICS = { |
| 42 | + "maxrss": RusageMetric("ru_maxrss", factor=1000, unit="B"), # KiB on linux |
| 43 | +} |
| 44 | + |
| 45 | +ALL_METRICS = {**PERF_METRICS, **RUSAGE_METRICS} |
| 46 | + |
| 47 | + |
| 48 | +def measure_perf(cmd: list[str], events: list[str]) -> dict[str, tuple[float, str]]: |
| 49 | + with tempfile.NamedTemporaryFile() as tmp: |
| 50 | + cmd = [ |
| 51 | + *["perf", "stat", "-j", "-o", tmp.name], |
| 52 | + *[arg for event in events for arg in ["-e", event]], |
| 53 | + *["--", *cmd], |
| 54 | + ] |
| 55 | + |
| 56 | + # Execute command |
| 57 | + env = os.environ.copy() |
| 58 | + env["LC_ALL"] = "C" # or else perf may output syntactically invalid json |
| 59 | + result = subprocess.run(cmd, env=env) |
| 60 | + if result.returncode != 0: |
| 61 | + sys.exit(result.returncode) |
| 62 | + |
| 63 | + # Collect results |
| 64 | + perf = {} |
| 65 | + for line in tmp: |
| 66 | + data = json.loads(line) |
| 67 | + if "event" in data and "counter-value" in data: |
| 68 | + perf[data["event"]] = float(data["counter-value"]), data["unit"] |
| 69 | + |
| 70 | + return perf |
| 71 | + |
| 72 | + |
| 73 | +@dataclass |
| 74 | +class Result: |
| 75 | + category: str |
| 76 | + value: float |
| 77 | + unit: str | None |
| 78 | + |
| 79 | + def fmt(self, topic: str) -> str: |
| 80 | + metric = f"{topic}//{self.category}" |
| 81 | + if self.unit is None: |
| 82 | + return json.dumps({"metric": metric, "value": self.value}) |
| 83 | + return json.dumps({"metric": metric, "value": self.value, "unit": self.unit}) |
| 84 | + |
| 85 | + |
| 86 | +def measure(cmd: list[str], metrics: list[str]) -> list[Result]: |
| 87 | + # Check args |
| 88 | + unknown_metrics = [] |
| 89 | + for metric in metrics: |
| 90 | + if metric not in RUSAGE_METRICS and metric not in PERF_METRICS: |
| 91 | + unknown_metrics.append(metric) |
| 92 | + if unknown_metrics: |
| 93 | + raise Exception(f"unknown metrics: {', '.join(unknown_metrics)}") |
| 94 | + |
| 95 | + # Prepare perf events |
| 96 | + events: list[str] = [] |
| 97 | + for metric in metrics: |
| 98 | + if info := PERF_METRICS.get(metric): |
| 99 | + events.append(info.event) |
| 100 | + |
| 101 | + # Measure |
| 102 | + perf = measure_perf(cmd, events) |
| 103 | + rusage = resource.getrusage(resource.RUSAGE_CHILDREN) |
| 104 | + |
| 105 | + # Extract results |
| 106 | + results = [] |
| 107 | + for metric in metrics: |
| 108 | + if info := PERF_METRICS.get(metric): |
| 109 | + if info.event in perf: |
| 110 | + value, unit = perf[info.event] |
| 111 | + else: |
| 112 | + # Without the corresponding permissions, |
| 113 | + # we only get access to the userspace versions of the counters. |
| 114 | + value, unit = perf[f"{info.event}:u"] |
| 115 | + |
| 116 | + value *= PERF_UNITS.get(unit, info.factor) |
| 117 | + results.append(Result(metric, value, info.unit)) |
| 118 | + |
| 119 | + if info := RUSAGE_METRICS.get(metric): |
| 120 | + value = getattr(rusage, info.name) * info.factor |
| 121 | + results.append(Result(metric, value, info.unit)) |
| 122 | + |
| 123 | + return results |
| 124 | + |
| 125 | + |
| 126 | +if __name__ == "__main__": |
| 127 | + parser = argparse.ArgumentParser( |
| 128 | + description=f"Measure resource usage of a command using perf and rusage. The results are appended to {OUTFILE.name}.", |
| 129 | + ) |
| 130 | + parser.add_argument( |
| 131 | + "-t", |
| 132 | + "--topic", |
| 133 | + action="append", |
| 134 | + default=[], |
| 135 | + help="topic prefix for the metrics", |
| 136 | + ) |
| 137 | + parser.add_argument( |
| 138 | + "-m", |
| 139 | + "--metric", |
| 140 | + action="append", |
| 141 | + default=[], |
| 142 | + help=f"metrics to measure. Can be specified multiple times. Available metrics: {', '.join(sorted(ALL_METRICS))}", |
| 143 | + ) |
| 144 | + parser.add_argument( |
| 145 | + "cmd", |
| 146 | + nargs="*", |
| 147 | + help="command to measure the resource usage of", |
| 148 | + ) |
| 149 | + args = parser.parse_args() |
| 150 | + |
| 151 | + topics: list[str] = args.topic |
| 152 | + metrics: list[str] = args.metric |
| 153 | + cmd: list[str] = args.cmd |
| 154 | + |
| 155 | + results = measure(cmd, metrics) |
| 156 | + |
| 157 | + with open(OUTFILE, "a+") as f: |
| 158 | + for result in results: |
| 159 | + for topic in topics: |
| 160 | + f.write(f"{result.fmt(topic)}\n") |
0 commit comments