CPU profiling

Naming the game's code

A sample in the game's code is named F_<hex> (AOT), or not named at all (JIT, NCE). The hex is the guest address, and the modules are laid out at the same bases as in the runtime, so the game's own symbol tables name it:

python3 tools/symbols.py work/Game 7100123450 71001a2b3c     # demangled names, as the game's modules have them
python3 tools/disasm.py  work/Game 7100123450 71001234f0     # the guest code of a range
python3 tools/disasm.py  work/Game nn::gfx::detail::Foo       # a whole function, by (sub)name

work/Game is the extracted dump (exefs/ + romfs/) or an NRO. Both read the modules through scarletnx --dump-modules (SNX_SCARLETNX names another binary) and cache them in ~/.cache/scarletnx/module-dumps. disasm.py needs llvm-objcopy and llvm-objdump. Many retail modules are stripped: then a function only has its address, and the guest disassembly (or the host code, perf annotate) is what tells it apart.

To see the host code the recompiler made for a function, disassemble the module itself:

llvm-objdump -d --disassemble-symbols=F_7100123450 "$games/<id>/<id>_code.so"

perf (Linux)

perf is the general tool on Linux: no rebuild, every thread, hardware counters.

Who can sample. kernel.perf_event_paranoid of 2 (the usual default) lets a user sample their own processes' user-space code; that is enough. -1 (root) adds kernel stacks and system-wide sampling.

A flat profile of a scene (the most useful first view, as the game's code has no reliable stacks):

"$g" --state-load=2000:1 --seconds=90 --fps-limit=0 --vsync=0 &
sleep 30                                                  # past loading, into the scene
perf record -F 999 -e cycles:u -p $! -o work/prof/perf.data -- sleep 30
perf report -i work/prof/perf.data --no-children --sort comm,dso,sym

Call stacks for the runtime's code. Use the Tracy build (frame pointers) and --call-graph fp:

perf record -F 999 -e cycles:u --call-graph fp -p PID -o work/prof/fp.data -- sleep 20
perf report -i work/prof/fp.data --children --sort sym

Stacks stop at the game's code: a runtime function called from the game (an SVC wrapper, an NVN handler, a hooked memcpy) shows its runtime callers up to the generated function, then breaks. On Intel, last-branch-record call stacks do not need frame pointers and see through the game's code too, a few calls deep:

perf record -F 999 -e cycles:u --call-graph lbr -p PID -o work/prof/lbr.data -- sleep 20

--call-graph dwarf copies the stack with each sample and unwinds with .eh_frame; it works for the runtime and the libraries, not through the module, which has none, and is heavy (keep the sample rate low).

Flame graphs. perf script -i work/prof/fp.data | stackcollapse-perf.pl | flamegraph.pl > work/prof/fg.svg (FlameGraph), or open the data in hotspot, which also has a per-thread timeline.

Counters. perf stat says why code is slow rather than where:

perf stat -e task-clock,cycles,instructions,branch-misses,cache-misses,context-switches,cpu-migrations \
    -p PID -- sleep 20
perf stat --per-thread -e task-clock -p PID -- sleep 10        # CPU time per guest and runtime thread

Low instructions per cycle in the game's code points at memory (guest memory accesses are plain loads from g_mem, GP(addr)); many context switches point at the guest's synchronization (try native_os_sync/native_cond_var, and look at the SVC zones in Tracy).

Annotate. perf annotate -i work/prof/perf.data -s F_7100123450 shows the hot instructions of a generated function; set it beside tools/disasm.py of the same address to read the guest code each host instruction came from.

profile_cpu.py: sampling without perf

Where perf is not allowed (a locked-down machine, a container), tools/profile_cpu.py samples a process on Linux x86-64 and AArch64 with a preload library (tools/cpu_sample.c) and each thread's own CPU clock (SIGPROF). Sleeping threads give no samples, so it measures CPU cost, not waits.

python3 tools/profile_cpu.py tune --out work/prof/ring-search               # once: size the rings
python3 tools/profile_cpu.py run --config work/prof/ring-search/winner.json \
    --out work/prof/capture -- "$g" --seconds=60 --fps-limit=0

The capture holds samples.bin (timestamp, host PC, TID, weight), maps.txt to resolve the PCs against, and sched.jsonl (per-thread CPU time, run-queue wait and context switches). Check samples.bin.json for drops after every real capture and raise the capacity if it reports any. The format and the recovery rules are in CPU sampling without perf.

pmcstat and DTrace (FreeBSD)

FreeBSD has no perf; it has hwpmc(4) with pmcstat(8), and DTrace. Both need root (or a user security.bsd settings allow), and the module loaded:

sudo kldload hwpmc
pmcstat -L | head                      # the events this CPU has

A flat profile of a running game (the PID is the <id> process):

sudo pmcstat -P cpu_clk_unhalted.thread_p -t PID -O work/prof/game.pmc    # Intel; AMD: ls_not_halted_cyc
# ... let the scene run, then Ctrl-C
pmcstat -R work/prof/game.pmc -g -D work/prof/gprof                        # gprof-style files per module
pmcstat -R work/prof/game.pmc -G work/prof/callgraph.txt                   # callers and callees, as text

-P samples the process's own threads (-S would sample the whole system). -t attaches to a PID; giving the command after the options starts it instead. pmcstat -R ... -T gives a live, top-like view of a log or of a live session (pmcstat -P event -t PID -T).

Call chains come from the frame pointers, so the Tracy build is again the one to use, and they stop at the game's code. For a flame graph, stackcollapse-pmc.pl from FlameGraph reads -G output.

DTrace samples with the profile provider and walks user stacks with frame pointers too:

sudo dtrace -p PID -n 'profile-997 /pid == $target/ { @[ufunc(uregs[R_PC])] = count(); } tick-30s { exit(0); }' \
    -o work/prof/funcs.txt
sudo dtrace -p PID -n 'profile-997 /pid == $target/ { @[ustack(32)] = count(); } tick-30s { exit(0); }' \
    -o work/prof/stacks.txt
stackcollapse.pl work/prof/stacks.txt | flamegraph.pl > work/prof/fg.svg

DTrace is also good at questions a sampler is not: how often a syscall is made and how long it takes (syscall:::entry /pid == $target/ { @[probefunc] = count(); }), or which thread waits on what (sched:::off-cpu).

Notes for FreeBSD:

Windows, macOS and Android

The JIT

The recompile compiles what its analysis finds; a function it missed is compiled at run time by the JIT, on the jit compile threads (background) and a jit miss thread (what a game thread is waiting for). Two costs follow:

  1. Compile time. A game thread that reaches a missed function waits for its compile. Tracy's jit miss ms, jit compile ms, jit queue depth and jit batch size show it; a hitch whose frame holds a jit miss ms spike is one. The settings jit_threads, jit_region_instructions, jit_live_budget and jit_opt trade compile time against code quality (Settings). tools/tune_jit_latency.py compares compile strategies offline on private snapshots with snx-bench-jit-latency.
  2. Unnamed code. The JIT's code is in anonymous memory. On Linux, perf_map=1 writes a perf map that names it for sampled profilers (Tracy); off, external profilers cannot name it. To profile it otherwise, make it AOT: the JIT records what it compiled, and an AOT pack links those functions into the game's module, where they have F_ names. A profile of the pack's run names them. Under the GDB stub, gdb_jit=1 registers each JIT object with GDB (gdb_jit.c), so a debugger can name and unwind them; it stops the game at every compile, so it is for inspection, not timing.

A profile in which [unknown] is large is usually JIT code: check its share before reading the rest.

Micro-benchmarks for CPU work

A change to a hot path is easier to measure outside the game, then confirmed in it:

These measure a named workload, not a game's frame rate.


Made from docs/dev/profiling.md at 69237645142c. GPL-3.0-or-later.