mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 13:38:36 +00:00
tools: frame rate of a D3D12-runtime run by draws a frame, and two runs side by side (TOOLS-D3D12-RUN-FPS)
tools/d3d12_run_fps.py reads the frame line the D3D12 runtime logs every few seconds (fps, ms a frame, preparing, copies, waiting on the GPU, copying back, draws a frame) and prints numbers only: the samples in the world (the first bucket's lower bound, 1000 draws a frame by default, leaves out menus and loading screens), the frame rate (median, slowest tenth, fastest tenth), the medians of where a frame goes, and the median frame rate per bucket of draws a frame. --compare puts a second run beside the first bucket by bucket and gives the change only where both runs have enough samples. Why: two runs of the game never show the same scenes for the same time, so their plain medians do not compare. Measured here on two real runs of one save (numbers only): plain medians 15.6 and 16.2 fps, but by bucket the second was 51%, 29%, 5% and 21% faster at 3-5k, 5-7k, 7-9k and 9k+ draws a frame: it had spent its time in busier scenes (median 7,676 draws against 5,132). It never prints a log line, a program name, an address or the path of a log; the log stays on the machine that made it. Standard library only. Reads UTF-8 and UTF-16 logs (a PowerShell redirection writes UTF-16) and strips terminal colour codes; a truncated last line is skipped. The pattern takes only what the runtime's format string writes (bounded lengths, nothing in front of the first number), so no other text in a log reads as a frame line. Test: python -I tests/test_d3d12_run_fps.py (16 tests on synthetic lines in the shape of the runtime's format string; no game files, no GPU). On main it fails at import: the tool does not exist there. Checked: python -I tests/test_d3d12_run_fps.py; python -I tests/test_text_write_line_endings.py; python -I scripts/check_no_game_data.py on the three files; eight deliberate breakages of the tool each fail a test. A second, fresh session reviewed the first version; its findings are fixed. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@ -185,3 +185,8 @@ with the fields of these sections: machine (OS, GPU, driver, RAM), the commit, h
|
||||
pre-compile, the OS and driver settings, every `LEONIDA_*` variable that differs from the defaults (never the
|
||||
watchdog's RVA values), and how far the run got with its frame rate. Keep logs, traces and screenshots on your machine
|
||||
([linux_proton.md](linux_proton.md#reporting-a-result)).
|
||||
|
||||
For a run of the D3D12 runtime (`d3d12/`), `python -I tools/d3d12_run_fps.py <log>` reads the frame lines of the
|
||||
launcher's log and gives the frame rate overall and by draws a frame. Two runs never show the same scenes for the same
|
||||
time, so their plain medians do not compare: `--compare <log B>` puts an A and a B side by side per bucket of draws.
|
||||
It prints numbers only, never a log line.
|
||||
|
||||
306
tests/test_d3d12_run_fps.py
Normal file
306
tests/test_d3d12_run_fps.py
Normal file
@ -0,0 +1,306 @@
|
||||
"""tools/d3d12_run_fps.py on synthetic logs: the frame line read, the buckets, the comparison, and no log text printed.
|
||||
|
||||
python -I tests/test_d3d12_run_fps.py
|
||||
|
||||
Each test writes a small log by hand in the shape the D3D12 runtime's frame line has (the format string in
|
||||
d3d12/crates/leonida-gpu/src/host.rs); no game files, no GPU.
|
||||
"""
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(HERE)
|
||||
sys.path.insert(0, os.path.join(ROOT, "tools"))
|
||||
|
||||
import d3d12_run_fps as run_fps
|
||||
|
||||
# A line the tool must never print: it stands for text the title itself would put in a log.
|
||||
SECRET = "Synthetic Title Text 42"
|
||||
STAMP = "2026-11-28T20:00:00.000000Z"
|
||||
|
||||
|
||||
def frame_text(fps, draws, preparing=20.0, copies_ms=8.0, copies_mb=40.0, textures_ms=1.0, textures_mb=2.0, gpu=1.5,
|
||||
back_ms=3.0, back_mb=0.5, ms=None):
|
||||
"""The frame line's own text, as the runtime's format string writes it."""
|
||||
ms = 1000.0 / fps if ms is None else ms
|
||||
return (f"{fps:.1f} fps, {ms:.1f} ms/frame ({preparing:.1f} preparing: copies {copies_ms:.1f} ms "
|
||||
f"{copies_mb:.1f} MB, textures {textures_ms:.1f} ms {textures_mb:.1f} MB; {gpu:.1f} on the GPU; "
|
||||
f"{back_ms:.1f} copying back {back_mb:.1f} MB), {draws} draws/frame, dropped 3 without a host pipeline "
|
||||
f"(0 being made) and 7 indirect")
|
||||
|
||||
|
||||
def frame_line(fps, draws, colour=False, **fields):
|
||||
"""One frame line with the timestamp, level and target that come before it."""
|
||||
text = frame_text(fps, draws, **fields)
|
||||
if colour: # as a terminal shows it: dimmed stamp and target, a green level, and a code inside the line itself
|
||||
dim, green, off = "\x1b[2m", "\x1b[32m", "\x1b[0m"
|
||||
text = text.replace(" fps,", f" fps{off},", 1)
|
||||
return f"{dim}{STAMP}{off} {green} INFO{off} {dim}leonida_gpu::host{off}{dim}:{off} {text}"
|
||||
return f"{STAMP} INFO leonida_gpu::host: {text}"
|
||||
|
||||
|
||||
def write_log(folder, name, lines, encoding="utf-8"):
|
||||
path = os.path.join(folder, name)
|
||||
with open(path, "wb") as f:
|
||||
f.write(("\n".join(lines) + "\n").encode(encoding))
|
||||
return path
|
||||
|
||||
|
||||
def run_tool(*argv):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
code = run_fps.main(list(argv))
|
||||
return code, out.getvalue()
|
||||
|
||||
|
||||
class ReadSamples(unittest.TestCase):
|
||||
def test_the_frame_line_is_read_field_by_field(self):
|
||||
line = frame_line(20.0, 4321, preparing=31.5, copies_ms=12.5, copies_mb=61.0, textures_ms=2.5,
|
||||
textures_mb=17.0, gpu=0.4, back_ms=5.5, back_mb=0.9)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
(s,) = run_fps.read_samples(write_log(tmp, "a.log", [line]))
|
||||
self.assertEqual(s, {"fps": 20.0, "frame_ms": 50.0, "preparing_ms": 31.5, "copies_ms": 12.5,
|
||||
"copies_mb": 61.0, "textures_ms": 2.5, "textures_mb": 17.0, "gpu_wait_ms": 0.4,
|
||||
"copy_back_ms": 5.5, "copy_back_mb": 0.9, "draws": 4321})
|
||||
self.assertIsInstance(s["draws"], int)
|
||||
|
||||
def test_other_lines_colour_codes_and_a_truncated_last_line(self):
|
||||
whole = frame_line(15.0, 9000)
|
||||
lines = [
|
||||
f"{STAMP} INFO leonida_gpu::host: host D3D12 device ready",
|
||||
frame_line(30.0, 12),
|
||||
frame_line(18.0, 6000, colour=True),
|
||||
f"{STAMP} INFO leonida_hle: {SECRET}",
|
||||
whole[:whole.index(" draws/frame")], # a crash cut the last line short, just before what ends the match
|
||||
]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
samples = run_fps.read_samples(write_log(tmp, "a.log", lines))
|
||||
self.assertEqual([(s["fps"], s["draws"]) for s in samples], [(30.0, 12), (18.0, 6000)])
|
||||
|
||||
def test_a_utf16_log_reads_the_same(self):
|
||||
lines = [frame_line(20.0, 4000), frame_line(10.0, 9500)]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
plain = run_fps.read_samples(write_log(tmp, "a.log", lines))
|
||||
wide = run_fps.read_samples(write_log(tmp, "b.log", lines, encoding="utf-16"))
|
||||
self.assertEqual(plain, wide)
|
||||
self.assertEqual(len(wide), 2)
|
||||
|
||||
def test_only_what_the_format_string_writes_is_a_frame_line(self):
|
||||
good = frame_text(20.0, 4000)
|
||||
lines = [
|
||||
"-" + good, # a sign in front: not the runtime's line
|
||||
"1e3" + good[4:], # "1e3 fps": the 3 alone must not read as the rate
|
||||
"." + good, # ".20.0 fps"
|
||||
"v" + good, # a word running into the number
|
||||
good.replace("4000 draws", "4" * 400 + " draws"), # a draws count no frame has
|
||||
"9" * 400 + good[4:], # a rate no frame has
|
||||
"7" * 400000, # a long run of digits must cost no time to refuse
|
||||
good, # the one real line, with nothing before it
|
||||
]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
began = time.perf_counter()
|
||||
samples = run_fps.read_samples(write_log(tmp, "a.log", lines))
|
||||
took = time.perf_counter() - began
|
||||
self.assertEqual([(s["fps"], s["draws"]) for s in samples], [(20.0, 4000)])
|
||||
self.assertLess(took, 5.0)
|
||||
|
||||
|
||||
class Summarize(unittest.TestCase):
|
||||
def test_menus_are_left_out_and_buckets_take_their_draws(self):
|
||||
lines = [frame_line(30.0, 13)] * 4 # a menu: under the first edge
|
||||
lines += [frame_line(f, 4000) for f in (24.0, 26.0, 28.0)]
|
||||
lines += [frame_line(f, 9500) for f in (12.0, 14.0)]
|
||||
lines += [frame_line(20.0, 5000)] # an edge belongs to the bucket it starts
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
s = run_fps.summarize(run_fps.read_samples(write_log(tmp, "a.log", lines)))
|
||||
self.assertEqual((s["frame_lines"], s["in_world"], s["min_draws"]), (10, 6, 1000))
|
||||
self.assertEqual(s["fps"], {"median": 22.0, "slowest_tenth": 12.0, "fastest_tenth": 28.0})
|
||||
by = {b["draws"]: (b["samples"], b["median_fps"]) for b in s["buckets"]}
|
||||
self.assertEqual(by, {"1000-2999": (0, None), "3000-4999": (3, 26.0), "5000-6999": (1, 20.0),
|
||||
"7000-8999": (0, None), "9000+": (2, 13.0)})
|
||||
self.assertEqual(s["medians"]["draws"], 4500.0)
|
||||
|
||||
def test_tenths_are_by_nearest_rank(self):
|
||||
twenty = [float(v) for v in range(1, 21)] # a tenth of twenty is two samples
|
||||
self.assertEqual(run_fps.tenth(twenty), 2.0)
|
||||
self.assertEqual(run_fps.tenth(twenty, fastest=True), 19.0)
|
||||
eleven = [float(v) for v in range(1, 12)] # a tenth of eleven is two: rounded up, not down
|
||||
self.assertEqual(run_fps.tenth(eleven), 2.0)
|
||||
self.assertEqual(run_fps.tenth(eleven, fastest=True), 10.0)
|
||||
self.assertEqual(run_fps.tenth([7.0]), 7.0)
|
||||
self.assertEqual(run_fps.tenth([3.0, 9.0]), 3.0)
|
||||
self.assertEqual(run_fps.tenth([3.0, 9.0], fastest=True), 9.0)
|
||||
|
||||
def test_the_first_edge_is_where_the_world_starts(self):
|
||||
rest = dict.fromkeys((f for f in run_fps.FIELDS if f not in ("fps", "draws")), 1.0)
|
||||
samples = [{"fps": fps, "draws": draws, **rest} for fps, draws in ((30.0, 500), (20.0, 1500), (10.0, 2500))]
|
||||
s = run_fps.summarize(samples, edges=(1000, 2000))
|
||||
self.assertEqual((s["in_world"], s["min_draws"]), (2, 1000))
|
||||
self.assertEqual([(b["draws"], b["samples"]) for b in s["buckets"]], [("1000-1999", 1), ("2000+", 1)])
|
||||
s = run_fps.summarize(samples, edges=(0, 2000))
|
||||
self.assertEqual((s["in_world"], s["min_draws"]), (3, 0))
|
||||
self.assertEqual([(b["draws"], b["samples"]) for b in s["buckets"]], [("0-1999", 2), ("2000+", 1)])
|
||||
|
||||
def test_a_log_without_frame_lines(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
log = write_log(tmp, "a.log", [f"{STAMP} INFO leonida_gpu::host: nothing yet"])
|
||||
s = run_fps.summarize(run_fps.read_samples(log))
|
||||
code, text = run_tool(log)
|
||||
self.assertEqual((s["frame_lines"], s["in_world"], s["fps"], s["medians"]), (0, 0, None, None))
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(text, "0 frame lines, 0 in the world (1000+ draws a frame)\n")
|
||||
|
||||
|
||||
class OneRun(unittest.TestCase):
|
||||
LINES = (
|
||||
[frame_line(30.0, 13)]
|
||||
+ [frame_line(f, 4000, preparing=30.0, copies_ms=12.0, copies_mb=50.0, textures_ms=2.0, gpu=0.5, back_ms=5.0)
|
||||
for f in (24.0, 26.0, 28.0)]
|
||||
+ [frame_line(12.0, 9500, preparing=44.0, copies_ms=20.0, copies_mb=80.0, textures_ms=3.0, gpu=1.5,
|
||||
back_ms=7.0)]
|
||||
+ [f"{STAMP} INFO leonida_hle: {SECRET}"]
|
||||
)
|
||||
|
||||
def test_the_whole_text_of_one_run(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
code, text = run_tool(write_log(tmp, "a.log", self.LINES))
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(text, (
|
||||
"5 frame lines, 4 in the world (1000+ draws a frame)\n"
|
||||
"frame rate: median 25.0 fps, slowest tenth 12.0, fastest tenth 28.0\n"
|
||||
"a frame (medians): 40.1 ms; preparing 30.0 ms (copies 12.0 ms, 50.0 MB; textures 2.0 ms); waiting on "
|
||||
"the GPU 0.5 ms; copying back 5.0 ms; 4000 draws\n"
|
||||
"by draws a frame:\n"
|
||||
" 1000-2999 - fps (0 samples)\n"
|
||||
" 3000-4999 26.0 fps (3 samples)\n"
|
||||
" 5000-6999 - fps (0 samples)\n"
|
||||
" 7000-8999 - fps (0 samples)\n"
|
||||
" 9000+ 12.0 fps (1 sample)\n"
|
||||
))
|
||||
|
||||
def test_edges_and_json_through_the_command_line(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
log = write_log(tmp, "a.log", self.LINES)
|
||||
code, text = run_tool(log, "--edges", "0,5000")
|
||||
json_code, as_json = run_tool(log, "--edges", "0,5000", "--json")
|
||||
self.assertEqual((code, json_code), (0, 0))
|
||||
self.assertIn("5 frame lines, 5 in the world (0+ draws a frame)\n", text)
|
||||
self.assertIn(" 0-4999 27.0 fps (4 samples)\n", text)
|
||||
self.assertIn(" 5000+ 12.0 fps (1 sample)\n", text)
|
||||
data = json.loads(as_json)
|
||||
self.assertEqual(sorted(data), ["a"])
|
||||
self.assertEqual(data["a"]["fps"], {"median": 26.0, "slowest_tenth": 12.0, "fastest_tenth": 30.0})
|
||||
self.assertEqual(data["a"]["buckets"], [{"draws": "0-4999", "samples": 4, "median_fps": 27.0},
|
||||
{"draws": "5000+", "samples": 1, "median_fps": 12.0}])
|
||||
for out in (text, as_json):
|
||||
self.assertNotIn(SECRET, out)
|
||||
self.assertNotIn(tmp, out)
|
||||
|
||||
|
||||
class Compare(unittest.TestCase):
|
||||
def logs(self, tmp):
|
||||
# Run A stands in a quiet place most of the time, run B in a busy one: B is faster in both places, and
|
||||
# its plain median is lower all the same.
|
||||
a = [frame_line(20.0, 4000)] * 8 + [frame_line(10.0, 9500)] * 5
|
||||
b = [frame_line(25.0, 4000)] * 5 + [frame_line(12.0, 9500)] * 9 + [frame_line(18.0, 6000)] * 2
|
||||
return write_log(tmp, "a.log", a), write_log(tmp, "b.log", b)
|
||||
|
||||
def test_like_for_like_where_the_plain_medians_mislead(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
a, b = (run_fps.summarize(run_fps.read_samples(p)) for p in self.logs(tmp))
|
||||
self.assertEqual((a["fps"]["median"], b["fps"]["median"]), (20.0, 12.0)) # the misleading reading
|
||||
c = run_fps.compare(a, b)
|
||||
rows = {r["draws"]: r for r in c["buckets"]}
|
||||
self.assertAlmostEqual(rows["3000-4999"]["change_percent"], 25.0)
|
||||
self.assertAlmostEqual(rows["9000+"]["change_percent"], 20.0)
|
||||
self.assertIsNone(rows["5000-6999"]["change_percent"]) # B alone was there, twice
|
||||
self.assertIsNone(rows["1000-2999"]["change_percent"]) # neither was
|
||||
self.assertEqual((c["compared"], c["b_faster"], c["b_slower"]), (2, 2, 0))
|
||||
back = run_fps.compare(b, a) # and the other way round, B is the slower
|
||||
self.assertEqual((back["compared"], back["b_faster"], back["b_slower"]), (2, 0, 2))
|
||||
|
||||
def test_a_bucket_needs_its_samples_in_both_runs(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
a, b = (run_fps.summarize(run_fps.read_samples(p)) for p in self.logs(tmp))
|
||||
self.assertEqual(run_fps.compare(a, b, min_samples=6)["compared"], 0) # 5 and 5 in the two buckets
|
||||
self.assertEqual(run_fps.compare(a, b, min_samples=2)["compared"], 2) # 6000 draws: A has none
|
||||
|
||||
def test_a_run_that_stood_still_is_not_divided_by(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
hung = write_log(tmp, "a.log", [frame_line(0.04, 4000, ms=25000.0)] * 5) # prints as 0.0 fps
|
||||
fine = write_log(tmp, "b.log", [frame_line(10.0, 4000)] * 5)
|
||||
a, b = (run_fps.summarize(run_fps.read_samples(p)) for p in (hung, fine))
|
||||
c = run_fps.compare(a, b)
|
||||
self.assertEqual(a["buckets"][1]["median_fps"], 0.0)
|
||||
self.assertEqual((c["compared"], c["buckets"][1]["change_percent"]), (0, None))
|
||||
|
||||
def test_text_and_json_say_the_same_and_print_no_log_text(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
a, b = self.logs(tmp)
|
||||
with open(a, "ab") as f:
|
||||
f.write(f"{STAMP} INFO leonida_hle: {SECRET}\n".encode())
|
||||
code, text = run_tool(a, "--compare", b)
|
||||
json_code, as_json = run_tool(a, "--compare", b, "--json")
|
||||
few_code, few = run_tool(a, "--compare", b, "--min-samples", "2")
|
||||
self.assertEqual((code, json_code, few_code), (0, 0, 0))
|
||||
data = json.loads(as_json)
|
||||
self.assertEqual(sorted(data), ["a", "b", "compare"])
|
||||
self.assertEqual((data["compare"]["compared"], data["compare"]["min_samples"]), (2, 5))
|
||||
self.assertEqual((data["a"]["in_world"], data["b"]["in_world"]), (13, 16))
|
||||
self.assertIn("run A: 13 frame lines, 13 in the world (1000+ draws a frame)\n", text)
|
||||
self.assertIn("run B: 16 frame lines, 16 in the world (1000+ draws a frame)\n", text)
|
||||
self.assertTrue(text.endswith(
|
||||
"B against A, by draws a frame (median fps, samples):\n"
|
||||
" 1000-2999 A - (0) B - (0) not compared\n"
|
||||
" 3000-4999 A 20.0 (8) B 25.0 (5) +25%\n"
|
||||
" 5000-6999 A - (0) B 18.0 (2) not compared\n"
|
||||
" 7000-8999 A - (0) B - (0) not compared\n"
|
||||
" 9000+ A 10.0 (5) B 12.0 (9) +20%\n"
|
||||
"buckets compared (5+ samples in both runs): 2; B faster in 2, slower in 0\n"))
|
||||
self.assertIn("buckets compared (2+ samples in both runs): 2; B faster in 2, slower in 0\n", few)
|
||||
for out in (text, as_json, few):
|
||||
self.assertNotIn(SECRET, out)
|
||||
self.assertNotIn("leonida_hle", out)
|
||||
self.assertNotIn(STAMP[:10], out)
|
||||
self.assertNotIn(tmp, out)
|
||||
|
||||
|
||||
class CommandLine(unittest.TestCase):
|
||||
def fails(self, *argv):
|
||||
err = io.StringIO()
|
||||
with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as stop:
|
||||
run_fps.main(list(argv))
|
||||
self.assertEqual(stop.exception.code, 2)
|
||||
return err.getvalue()
|
||||
|
||||
def test_a_missing_log_is_refused_without_its_path(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
log = write_log(tmp, "a.log", [frame_line(20.0, 4000)])
|
||||
missing = os.path.join(tmp, "none.log")
|
||||
first = self.fails(missing)
|
||||
second = self.fails(log, "--compare", missing)
|
||||
self.assertIn("cannot read the log:", first)
|
||||
self.assertIn("cannot read the second log:", second)
|
||||
for err in (first, second):
|
||||
self.assertNotIn(tmp, err)
|
||||
self.assertNotIn("none.log", err)
|
||||
|
||||
def test_bad_options_are_refused(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
log = write_log(tmp, "a.log", [frame_line(20.0, 4000)])
|
||||
self.assertIn("ascending", self.fails(log, "--edges", "3000,1000"))
|
||||
self.assertIn("ascending", self.fails(log, "--edges=-5,1000"))
|
||||
self.assertIn("whole numbers", self.fails(log, "--edges", "1000,many"))
|
||||
self.assertIn("whole numbers", self.fails(log, "--edges", ""))
|
||||
self.assertIn("--min-samples must be 1 or more", self.fails(log, "--compare", log, "--min-samples", "0"))
|
||||
self.assertIn("--min-samples needs --compare", self.fails(log, "--min-samples", "3"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
201
tools/d3d12_run_fps.py
Normal file
201
tools/d3d12_run_fps.py
Normal file
@ -0,0 +1,201 @@
|
||||
"""Frame rate of one D3D12-runtime run by scene load: numbers only, never log text.
|
||||
|
||||
python -I tools/d3d12_run_fps.py <log> [--compare <log B> [--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-<stamp>.log`, d3d12/scripts/play-nvidia.ps1):
|
||||
|
||||
<fps> fps, <ms> ms/frame (<ms> preparing: copies <ms> ms <MB> MB, textures <ms> ms <MB> MB; <ms> on the GPU;
|
||||
<ms> copying back <MB> MB), <n> draws/frame, ...
|
||||
|
||||
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. 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").
|
||||
|
||||
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; a truncated last line (the shape a crash
|
||||
leaves) is skipped.
|
||||
"""
|
||||
|
||||
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. The lengths are bounded and the first number must not continue a
|
||||
# word, a sign or another number, so that no other text in a log reads as a frame line or costs time to refuse.
|
||||
NUMBER = r"(\d{1,12}(?:\.\d{1,3})?)"
|
||||
FRAME_LINE = re.compile(
|
||||
rf"(?<![\w.+-]){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"
|
||||
)
|
||||
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):
|
||||
m = FRAME_LINE.search(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); waiting on "
|
||||
f"the GPU {m['gpu_wait_ms']:.1f} ms; copying back {m['copy_back_ms']:.1f} ms; {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"
|
||||
|
||||
|
||||
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 main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
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-<stamp>.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=int,
|
||||
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 = parser.parse_args(argv)
|
||||
if args.min_samples is not None and not args.compare:
|
||||
parser.error("--min-samples needs --compare")
|
||||
if args.min_samples is not None and args.min_samples < 1:
|
||||
parser.error("--min-samples must be 1 or more")
|
||||
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.error(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__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user