"""Compare explicit CPU counters, never infer CPU cost from throughput alone.""" from fractions import Fraction def accounting(record): for key in ("workload", "scope"): if not isinstance(record[key], str) or not record[key].strip(): raise ValueError(key + " must name the measured work/accounting scope") for key in ("completed_requests", "elapsed_ns", "cpu_ns"): value = record[key] if type(value) is not int: raise TypeError(key + " must be an integer") if value < 0 or (key != "cpu_ns" and value == 0): raise ValueError(key + " is outside the accounting domain") n, wall, cpu = (record[k] for k in ("completed_requests", "elapsed_ns", "cpu_ns")) return { **{key: record[key] for key in ("workload", "scope", "completed_requests", "elapsed_ns", "cpu_ns")}, "throughput_qps": str(Fraction(n * 10**9, wall)), "cpu_ns_per_request": str(Fraction(cpu, n)), "average_cpu_cores": str(Fraction(cpu, wall)), } def compare(baseline, candidate): left, right = accounting(baseline), accounting(candidate) for key in ("workload", "scope", "completed_requests"): if left[key] != right[key]: raise ValueError("comparison requires matching " + key) cpu_ratio = (str(Fraction(right["cpu_ns"], left["cpu_ns"])) if left["cpu_ns"] else None) return { "baseline": left, "candidate": right, "elapsed_time_ratio": str(Fraction(right["elapsed_ns"], left["elapsed_ns"])), "cpu_time_ratio": cpu_ratio, "cpu_ratio_status": "defined" if cpu_ratio is not None else "zero-baseline-counter", } def examples(): def record(wall, cpu): return {"workload": "constructed-equal-work", "scope": "whole-worker-group", "completed_requests": 1000, "elapsed_ns": wall * 10**9, "cpu_ns": cpu * 10**9} return { "kind": "synthetic-arithmetic", "schema_version": 1, "cases": [ {"case": "faster-but-more-cpu", "result": compare(record(10, 10), record(5, 20))}, {"case": "same-throughput-less-cpu", "result": compare(record(10, 10), record(10, 5))}, {"case": "zero-baseline-unresolved", "result": compare(record(10, 0), record(5, 1))}, ], "limits": "Prescribed counters, not measured cache performance. Matching labels cannot prove complete or comparable instrumentation. Nanosecond units do not imply nanosecond accuracy; zero counters do not establish zero cost.", } if __name__ == "__main__": import json print(json.dumps(examples(), indent=2))