"""Frame rate of one D3D12-runtime run by scene load: numbers only, never log text. python -I tools/d3d12_run_fps.py [--compare [--min-samples N]] [--edges A,B,...] [--json] Reads the frame line the D3D12 runtime logs every few seconds (d3d12/crates/leonida-gpu/src/host.rs), in the log the launchers keep (`play-.log`, d3d12/scripts/play-nvidia.ps1): fps, ms/frame ( preparing: copies ms MB, textures ms MB; on the GPU; copying back MB), draws/frame, dropped ... and prints, for the samples in the world, how many there are, the frame rate (median, slowest tenth, fastest tenth), the medians of a frame's time, of the time preparing, of the copies and of the time waiting on the GPU, and the median frame rate per bucket of draws a frame. The buckets' lower bounds are `--edges` (1000,3000,5000,7000,9000 by default); a sample under the first is not in the world: menus and loading screens draw a few dozen times a frame. Why per bucket: two runs of the game never show the same scenes for the same time, so their plain medians do not compare. A run that spends its time in a busy street reads slower than one that stands in a room, whatever was changed. `--compare` puts a second run beside the first, bucket by bucket, and gives the change only for buckets with at least `--min-samples` samples (5 by default) in both runs: the comparison of an A and a B that a game-run test asks for (two `RUN` blocks, docs/agent_collaboration.md). It never prints a log line, nor the path of a log, nor an argument it was given: an error names the kind of mistake only. The log can quote what the title prints, so it stays on the machine that made it: share these numbers in issues and pull requests, not the file (AGENTS.md, "No game data"). A frame line counts only where the runtime's logger wrote it: at the start of a line, or after the time stamp, level and target of the `leonida_gpu::host` message (`victory_gpu::host` in the forks this runtime came from). The same words inside another message are not read. A last line the writer did not finish (no line end: the shape a crash leaves) is skipped. Standard library only; reads files, never runs them. The log may be UTF-8 or UTF-16 with a byte-order mark (what a PowerShell redirection writes) and may carry terminal colour codes. """ from __future__ import annotations import argparse import json import re import statistics import sys ANSI = re.compile(r"\x1b\[[0-9;]*m") # What the runtime's `{:.1}` and `{:.0}` print, with bounded lengths. NUMBER = r"(\d{1,12}(?:\.\d{1,3})?)" FRAME_LINE = re.compile( r"(?:\S+\s+INFO\s+(?:leonida|victory)_gpu::host:\s+)?" rf"{NUMBER} fps, {NUMBER} ms/frame \({NUMBER} preparing: copies {NUMBER} ms {NUMBER} MB, " rf"textures {NUMBER} ms {NUMBER} MB; {NUMBER} on the GPU; {NUMBER} copying back {NUMBER} MB\), " r"(\d{1,12}) draws/frame, dropped " ) FIELDS = ("fps", "frame_ms", "preparing_ms", "copies_ms", "copies_mb", "textures_ms", "textures_mb", "gpu_wait_ms", "copy_back_ms", "copy_back_mb", "draws") DEFAULT_EDGES = (1000, 3000, 5000, 7000, 9000) def _lines(path): """The file's lines: UTF-8, or UTF-16 with a byte-order mark.""" with open(path, "rb") as raw: head = raw.read(2) encoding = "utf-16" if head in (b"\xff\xfe", b"\xfe\xff") else "utf-8-sig" with open(path, encoding=encoding, errors="replace") as f: yield from f def read_samples(path) -> list[dict]: """One dict per frame line of the log, in the order logged.""" samples = [] for line in _lines(path): if not line.endswith("\n"): # the last line, cut short: not a whole frame line whatever it holds continue m = FRAME_LINE.match(ANSI.sub("", line)) if m: sample = {name: float(value) for name, value in zip(FIELDS, m.groups())} sample["draws"] = int(m.group(len(FIELDS))) samples.append(sample) return samples def tenth(values, fastest=False): """The value a tenth of the samples are at or below (`fastest`: at or above), by nearest rank.""" ordered = sorted(values, reverse=fastest) return ordered[-(-len(ordered) // 10) - 1] def bucket_names(edges) -> list[str]: return [f"{lo}-{hi - 1}" for lo, hi in zip(edges, edges[1:])] + [f"{edges[-1]}+"] def summarize(samples, edges=DEFAULT_EDGES) -> dict: """The numbers of one run. `edges` are the buckets' lower bounds, ascending; the world starts at the first.""" world = [s for s in samples if s["draws"] >= edges[0]] out = {"frame_lines": len(samples), "min_draws": edges[0], "in_world": len(world), "fps": None, "medians": None, "buckets": []} if world: fps = [s["fps"] for s in world] out["fps"] = {"median": statistics.median(fps), "slowest_tenth": tenth(fps), "fastest_tenth": tenth(fps, fastest=True)} out["medians"] = {name: statistics.median(s[name] for s in world) for name in FIELDS if name != "fps"} bounds = list(edges) + [None] for name, lo, hi in zip(bucket_names(edges), bounds, bounds[1:]): inside = [s["fps"] for s in world if s["draws"] >= lo and (hi is None or s["draws"] < hi)] out["buckets"].append({"draws": name, "samples": len(inside), "median_fps": statistics.median(inside) if inside else None}) return out def compare(a: dict, b: dict, min_samples: int = 5) -> dict: """Run B against run A per bucket. A bucket is compared with `min_samples` samples in both and A above 0 fps.""" rows = [] for ba, bb in zip(a["buckets"], b["buckets"]): both = ba["samples"] >= min_samples and bb["samples"] >= min_samples and ba["median_fps"] > 0 change = (bb["median_fps"] / ba["median_fps"] - 1) * 100 if both else None rows.append({"draws": ba["draws"], "a_samples": ba["samples"], "a_median_fps": ba["median_fps"], "b_samples": bb["samples"], "b_median_fps": bb["median_fps"], "change_percent": change}) compared = [r["change_percent"] for r in rows if r["change_percent"] is not None] return {"min_samples": min_samples, "buckets": rows, "compared": len(compared), "b_faster": sum(c > 0 for c in compared), "b_slower": sum(c < 0 for c in compared)} def _fps(value) -> str: return "-" if value is None else f"{value:.1f}" def _count(n: int, noun: str) -> str: return f"{n} {noun}" if n == 1 else f"{n} {noun}s" def render_run(s: dict, label: str = "") -> str: head = f"run {label}: " if label else "" out = [f"{head}{_count(s['frame_lines'], 'frame line')}, {s['in_world']} in the world " f"({s['min_draws']}+ draws a frame)"] if not s["in_world"]: return "\n".join(out) + "\n" m = s["medians"] out.append(f"frame rate: median {s['fps']['median']:.1f} fps, slowest tenth {s['fps']['slowest_tenth']:.1f}, " f"fastest tenth {s['fps']['fastest_tenth']:.1f}") out.append(f"a frame (medians): {m['frame_ms']:.1f} ms; preparing {m['preparing_ms']:.1f} ms (copies " f"{m['copies_ms']:.1f} ms, {m['copies_mb']:.1f} MB; textures {m['textures_ms']:.1f} ms, " f"{m['textures_mb']:.1f} MB); waiting on the GPU {m['gpu_wait_ms']:.1f} ms; copying back " f"{m['copy_back_ms']:.1f} ms, {m['copy_back_mb']:.1f} MB; {m['draws']:.0f} draws") out.append("by draws a frame:") for b in s["buckets"]: out.append(f" {b['draws']:>11} {_fps(b['median_fps']):>5} fps ({_count(b['samples'], 'sample')})") return "\n".join(out) + "\n" def render_compare(c: dict) -> str: out = ["B against A, by draws a frame (median fps, samples):"] for r in c["buckets"]: change = "not compared" if r["change_percent"] is None else f"{r['change_percent']:+.0f}%" out.append(f" {r['draws']:>11} A {_fps(r['a_median_fps']):>5} ({r['a_samples']}) " f"B {_fps(r['b_median_fps']):>5} ({r['b_samples']}) {change}") out.append(f"buckets compared ({c['min_samples']}+ samples in both runs): {c['compared']}; B faster in " f"{c['b_faster']}, slower in {c['b_slower']}") return "\n".join(out) + "\n" # The two argument types say what is wrong without the text given: argparse's own message for a bad `type=int` # quotes it, and a path typed in the wrong place must not come back in an error. Their texts are `_Parser.FIXED`. def _edges(text: str) -> tuple[int, ...]: try: edges = tuple(int(part) for part in text.split(",")) except ValueError: raise argparse.ArgumentTypeError("whole numbers separated by commas") from None if edges[0] < 0 or any(lo >= hi for lo, hi in zip(edges, edges[1:])): raise argparse.ArgumentTypeError("ascending numbers, the first 0 or more") return edges def _samples(text: str) -> int: try: n = int(text) except ValueError: n = 0 if n < 1: raise argparse.ArgumentTypeError("a whole number, 1 or more") return n class _Parser(argparse.ArgumentParser): """An `ArgumentParser` whose errors never hold what was typed. argparse quotes the text it could not use in several of its own messages (`--json=` gives "ignored explicit argument ''", and so does `--help=`). Here an error argparse raises is rewritten from a short list of fixed texts, with the option's own name where it names one; anything not on the list becomes "not understood". The tool's own errors go through `fail`, which prints them as they are. """ FIXED = ("whole numbers separated by commas", "ascending numbers, the first 0 or more", "a whole number, 1 or more") def error(self, message): for action in self._actions: head = f"argument {'/'.join(action.option_strings) or action.dest}: " if message.startswith(head): rest = message[len(head):] if rest in self.FIXED: said = rest elif rest.startswith("ignored explicit argument"): said = "takes no value" elif rest.startswith("expected"): said = "needs a value" else: said = "not understood" self.fail(head + said) if message.startswith("the following arguments are required"): self.fail("a log is needed") self.fail("the arguments were not understood") def fail(self, message): super().error(message) def main(argv=None) -> int: parser = _Parser( allow_abbrev=False, description="Frame rate of a D3D12-runtime run from the frame lines of its log, overall and by draws a " "frame, so that two runs compare like for like. It never prints a log line: the log can quote " "what the title prints and stays local; share these numbers, not the file.") parser.add_argument("log", help="the run's log (play-.log)") parser.add_argument("--compare", metavar="LOG_B", help="a second run's log, compared bucket by bucket") parser.add_argument("--edges", type=_edges, default=DEFAULT_EDGES, help="the buckets' lower bounds in draws a frame; samples under the first are left out " "(default 1000,3000,5000,7000,9000)") parser.add_argument("--min-samples", type=_samples, help="with --compare, the samples a bucket needs in both runs (default 5)") parser.add_argument("--json", action="store_true", help="print the numbers as JSON") args, unknown = parser.parse_known_args(argv) if unknown: # argparse would quote them, and one of them may be a path parser.fail(f"{_count(len(unknown), 'argument')} not understood: one log, and a second after --compare") if args.min_samples is not None and not args.compare: parser.fail("--min-samples needs --compare") runs = [] for which, path in (("the log", args.log), ("the second log", args.compare)): if path is None: continue try: runs.append(summarize(read_samples(path), args.edges)) except OSError as e: # the path is not printed: it is the user's own folder names parser.fail(f"cannot read {which}: {e.strerror}") result = {"a": runs[0]} if args.compare: result["b"] = runs[1] result["compare"] = compare(runs[0], runs[1], 5 if args.min_samples is None else args.min_samples) if args.json: sys.stdout.write(json.dumps(result, indent=1) + "\n") elif args.compare: sys.stdout.write(render_run(runs[0], "A") + render_run(runs[1], "B") + render_compare(result["compare"])) else: sys.stdout.write(render_run(runs[0])) return 0 if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main())