metal-gpu-trace
[test]
Measure how a Wine or macOS program uses the GPU on an Apple silicon Mac, from the command line or through an AI
coding agent: GPU time per frame, frame pacing, FPS and memory, recorded with Instruments' Metal System Trace; whether
a translation layer (DXMT, Mullion, MoltenVK) splits the work into too many short encoders; Metal
.gputrace captures read without Xcode; and Apple's published facts on each GPU family to read the numbers against.
Python 3.9+ standard library, zsh, and Xcode (for xctrace). MIT license. Español.
Recording
Arguments: label, seconds, a Wine directory holding bin/wine (or native), the Wine prefix, the working directory,
the program and its arguments. Without PERF_OUT, runs go to ./perf-runs. Reading the trace afterwards takes about
a minute on an M1 Pro (87 s for a 10 s recording); through the MCP server the whole call times out after 10 s per
recorded second plus 120 s, and an overrun recording leaves no files behind. One recording runs at a time; keep other GPU work off the Mac while it records.
Under Wine, give it 30 s: Wine's start-up takes part of the recording. A recording with under 100 frames is too short
to compare.
Disk use
Each recording keeps a JSON summary and three CSVs, about 2 MB for 10 s (most of it the Metal memory samples). The
.trace (tens to hundreds of MB) is deleted unless KEEP_TRACE=1. KEEP_RUNS=N keeps only the newest N recordings. PERF_MEMORY=0 skips the Metal memory table, the slowest to read:
the summary then has no metal_memory_mib and there is no memory CSV (41 % faster to summarize a 626 MB trace).
The MCP tools perf_record and perf_baseline_record offer the same as memory=false.
MCP server
Install
The server runs with uvx from PyPI, with nothing to clone
(brew install uv installs it). Recording also needs Xcode installed (xcrun xctrace version prints a version).
This is the command each client below runs. Desktop apps do not see Homebrew's PATH: give them the full path that
which uvx prints (/opt/homebrew/bin/uvx on Apple silicon). uvx keeps the version it first downloaded; run
the command once with --refresh after uvx to get the latest. uvx [email protected] pins a version.
The server reads these environment variables:
Claude Code
claude mcp list shows metal-trace as connected. --scope user makes it available in every project; leave it out
to add it to the current project only.
Windows
On Windows the server records native programs (perf_record_windows.py); no Wine and no Metal. METAL_TRACE_WINE is not needed: perf_record and perf_attach use native. METAL_TRACE_READ is separated by ;.
Frames come from Intel's PresentMon console application (MIT): one row per Present() of the process, with MsBetweenPresents and the GPU time MsGPUTime. Download PresentMon-<version>-x64.exe from its releases, check its SHA-256 against the one GitHub shows, and call the presentmon_install tool, or put it in %LOCALAPPDATA%\metal-gpu-trace or on PATH, or point PRESENTMON_EXE at it. The user must be an administrator or in the "Performance Log Users" group. Without PresentMon the summary falls back to DWM composition intervals (gpu.source is dwm-composition): they cover the whole desktop, miss games in exclusive full screen, and carry no GPU time. With neither a frame log, PresentMon nor DWM samples, a recording fails; it never invents frames.
What cannot be measured is null, not zero: the 1% low needs 100 frames and the 0.1% low 1000; stutter rate and jitter need two frames; thermal_throttling_detected needs GPU times; a drawstress log holds one mean per line, so its summary (gpu.frame_times) has no frame-level percentiles, stutter or jitter. DWM keeps only intervals between consecutive composed frames and drops a jump of several frames. perf_diagnose calls a large working set with uneven frame times MEMORY_PRESSURE_SUSPECTED: a suspicion, since memory bandwidth is not measured.
To run from a clone instead of PyPI (needs Python 3.9 or newer):
In JSON clients use "command": "uvx" (or the full path where uvx prints) and Windows paths with doubled backslashes. Claude Desktop reads %APPDATA%\Claude\claude_desktop_config.json. Run the Windows tests with python -m pytest test_perf_record_windows.py.
Claude Desktop, Cursor and other JSON clients
These apps do not expand ~ or $HOME: write absolute paths.
Codex CLI
In ~/.codex/config.toml:
Tools
perf_record takes workload, api (mtl, mtl-x64, vk, d3d11 or d3d12), dim, size and example instead of
program, to record a fetched test program (workload_list says what each has). mtl-x64 is native Metal built for
x86_64 and run under Rosetta, like Wine's programs; size ("1920x1080") sets drawstress's window. The first workload is bgfx's
17-drawstress (BSD-2, 9.3 MB),
built from source by .github/workflows/workloads.yml: a grid of cubes, dim³ draws per frame, with its shaders
inside the program. The compare-layer prompt (/metal-trace:compare-layer drawstress d3d12 in Claude Code) records it
in native Metal and under the Wine in METAL_TRACE_WINE, then runs perf_diagnose and perf_compare.
The second workload, bgfx-examples (55 MiB), holds thirty bgfx examples, each a different load (many cubes, textures,
render-target chains, a G-buffer, compute, reflective shadow maps, post-processing, draws the GPU decides, text and
interface, shadows, transparency, GPU read-back, virtual textures, upscaling, texture formats, occlusion queries, tessellation,
multiple windows, off-screen rendering; the last twenty-one measured in
native Metal and Wine D3D12 only, example_traits in workload_list gives each one's class and encoders per frame in both,
and 40-svt writes a 370 MB tile cache to temp/ in the workload's folder on its first run):
perf_record(workload="bgfx-examples", api="d3d12", example="21-deferred"). Two macOS levers change the Mac under a
recording: memory_free_pct (20 to 60) holds the whole Mac at that percentage of RAM free (memory_pressure), and
background runs the program under taskpolicy -b, a hard throttle. A small GPU-bound program does not feel the first
(drawstress stayed at 728 FPS and its resident memory fell); the second slows it several times over. Repeat a run that
uses either.
The third workload, godot, is a lit 3D scene a real engine builds from code (Godot 4.7.2, Forward+): 400 meshes, 8 lights,
a shadowed sun, api="mtl" for Godot's Metal driver and api="d3d12" under Wine for its Direct3D 12 driver, with
args="-- meshes=800 lights=16" to change it. workload_fetch("godot") keeps the 10 KB project from this repository's release and
downloads Godot's official macOS (171 MB) and Windows (86 MB) builds from godotengine/godot-builds, checking the SHA-512
this package pins; it needs about 257 MB and some seconds. The scene has no imported assets, so Godot does not import anything.
Godot compiles its pipelines on every start, which makes it a case for perf_cold_warm: its shader-compile hitches came back
unchanged in the second run.
Reading the numbers across runs
- A summary says where it ran and what the GPU did:
machine (chip, cores, RAM, macOS, screen_locked), gpu_activity
(utilization of the device, renderer and tiler, split scenes, GPU recoveries: it covers the whole GPU, not only the
program), resource_allocations (allocation events per frame, by type; a running total, not memory in use) and
command_buffer_errors.
- A locked Mac session leaves native Metal windows unpaced: 3 000 to 4 000 FPS against 120 with vsync, on the same
examples. Record with the Mac unlocked;
perf_compare returns screen when one run was recorded locked and the other not.
- GPU ms per frame follow the GPU's performance state: a run paced at 120 FPS sits in Minimum and takes more ms for
the same work (21-deferred: 1.75 ms paced, 0.27 ms unpaced).
perf_compare returns gpu_state when two runs sat in
different states, and perf_diagnose returns display_synced_hz when the FPS sits on a display rate. Compare runs paced
alike: native Metal and D3D12 under Wine with Mullion, both at 120 FPS, do compare.
- With
counters=true, each listed hitch also has top_limiter: the Limiter counter with the highest mean over the interval
before it (window_ms, read in whole 10 ms bins; null when no sample falls in it), which can differ from the whole run's
main limiter.
api=vk runs the same program through Vulkan on MoltenVK. MoltenVK is not shipped: set METAL_TRACE_MOLTENVK to a
directory (no spaces) holding an arm64 libMoltenVK.dylib, such as the one in a Vulkan SDK or brew install molten-vk.
The run's layer names MoltenVK with the library's SHA-256, so perf_compare against a native Metal run says it
compares two layers. In one measurement at dim=20, 10 s each: native Metal 2 encoders per frame; MoltenVK 13, 91 % of
them short, and the GPU idle 89 % of the time (perf_diagnose: too_many_short_encoders true). One pair of runs, not a
benchmark.
api=vk is native only. drawstress.exe --vk under Wine needs a Wine built with Vulkan: the Wine of DXMT and Apple's
Game Porting Toolkit were tried and both log Wine was built without Vulkan support, so the recording holds no GPU
frames. CrossOver's Wine has Vulkan but runs only inside one of its bottles, which was not tried.
The same facts are MCP resources: metal-trace://gpu-families (all) and metal-trace://gpu-families/apple7 to Each saved run is a resource too: metal-trace://runs/<run> reads its summary.
apple10. They restate Apple's Metal Feature Set Tables
of 21 May 2026, MTLGPUFamily and the
M3 tech talk; check a device with supportsFamily.
How it follows the MCP specification and
Claude Code's limits:
- stdout carries only MCP messages; each tool call logs one line to stderr (
METAL_TRACE_LOG=off silences it), with
no arguments or paths.
- Lists come in pages (
offset, limit, default 50, at most 500) with total and next_offset; a result over
40 000 characters is refused with a hint to ask for a smaller page.
- Files are read only inside
METAL_TRACE_OUT and the directories in METAL_TRACE_READ (separated by :).
- Failures come back as
isError results that say what to do, without stack traces or local paths. Summaries cut
absolute paths to file names, so they can be shared.
- Every
xctrace call has a timeout.
HTTP
METAL_TRACE_TOKEN=<secret of 16+ characters> metal-gpu-trace --http [--port N] serves the same tools at
POST http://127.0.0.1:8765/mcp (Streamable HTTP, one JSON reply per request), for a client on the same Mac that cannot
start a stdio server. Every request needs Authorization: Bearer <token>. It listens on 127.0.0.1 only, refuses a
request whose Host or Origin is not localhost or 127.0.0.1 (DNS rebinding), and does not start without the token. Cancel
a running call with notifications/cancelled from another connection. There is no progress stream over HTTP, and no
remote access: reach another Mac through an SSH tunnel (ssh -L 8765:127.0.0.1:8765 mac), not by opening the port.
Windows tests on a real machine
GitHub's windows-latest has no GPU and no desktop session, so PresentMon and DWM recordings are only tested on a real
Windows machine. windows/winbridge-run-tests.ps1 updates a checkout there and runs test_perf_record_windows.py; it is
written as a WinBridge task (fixed name, script pinned by SHA-256, no
arguments). To register it, copy it to the laptop, set $repo to the checkout's path, take its hash there with
Get-FileHash <file> -Algorithm SHA256 (Git may have changed the line endings, so the hash of the copy in this repo is
not the one to use), and add a [tasks.<name>] table with script and sha256 to the agent's TOML.
CI gate
metal-gpu-trace check RUN BASELINE [--margin-pct N] runs perf_check without a client and prints one JSON line
(verdict, reasons, hints). Exit code 0: same or improved; 1: regressed; 2: could not be judged (no such run or
reference, or under 100 frames). Runs are read from METAL_TRACE_OUT. Recording needs Instruments, so the job runs on
a self-hosted macOS runner:
Credits
- The record layout of a
.gputrace command stream follows tmc/gputrace (MIT); no
code is copied. The call ids were matched against Xcode's command list on macOS 27.0.1.
- GPU family facts: Apple's documents linked above, restated, not quoted.