perfr, from Orbit · Post 28

The Hooks Were Already There

Two game engines in one day, and not a single scope added to either. Bevy already wraps every system, schedule and render pass in a tracing span; Godot already wraps its main loop, renderer and script VM in macros that choose a profiler at build time. Both engines left a seam for exactly this, so perfr became a destination for the instrumentation they ship: a tracing-subscriber layer for one, a fourth value of the profiler= option for the other.

291lines of Rust in the tracing layer, tests aside
208lines of C++ and SCons in Godot, across five files
3,000scopes a frame from bevy_city, 44,800 entities
60distinct engine zones a frame from Godot's shooter demo

A profiler with a manual API invites a particular mistake: you open the engine's source and start adding scopes. The main loop, the renderer, the physics step, each one a judgement about where the interesting boundaries are. The engines have already made those judgements. Bevy made them for Tracy and the Chrome trace format, Godot made them for Tracy, Perfetto and Instruments, Unreal made them for its external profiler interface a decade ago. What each one also made, without quite saying so, is a seam where another destination can be attached. The work this post describes is finding the seam in two engines and fitting perfr into it, and the interesting parts are the three places where the fit was not quite flush: what to call a scope, where a frame ends, and when a name may be formatted.

Bevy: a layer on the subscriber

Bevy's instrumentation is the tracing crate's. Behind the trace cargo feature, info_span! wraps every system run (system, with the system's path in a name field), every schedule (schedule), the application update (update), each sub app, the render graph's passes, queue_submit, present_frames, parallel query iteration. Without the feature the macros compile to nothing. Its trace_tracy and trace_chrome features each add a tracing-subscriber layer to the subscriber that LogPlugin builds, and since Bevy 0.14 that plugin has a public slot for one more: LogPlugin::custom_layer, a function from the app to a boxed layer.

So the whole integration, from the application's side, is a feature in the example's manifest and one plugin setting:

#[cfg(feature = "perfr")]
let default_plugins = default_plugins.set(bevy::log::LogPlugin {
    custom_layer: |_app| Some(Box::new(
        perfr_tracing::PerfrLayer::new().frame_mark_on_exit("update"),
    )),
    ..default()
});

The layer is perfr-tracing, 291 lines that know nothing about Bevy. It implements three callbacks. on_new_span formats the scope's name once and stores it in the span's extensions. on_enter starts a perfr scope with that name and pushes the handle on a thread-local stack; on_exit pops it and stops the scope. The stack exists because tracing reports an exit by span id, not by handle, and because a span can be entered on several threads at once (a system span is one object per system, entered on whichever worker runs it), so the handle has to live with the thread that did the entering, not with the span.

fn on_enter(&self, id: &Id, ctx: Context<'_, S>) {
    if !perfr_api::capturing() { return; }           // one load, one branch
    let span = ctx.span(id)?;
    let scope = span.extensions().get::<ScopeName>()?;  // formatted at on_new_span
    let handle = perfr_api::start(scope.name.as_bytes());
    ENTERED.with(|e| e.borrow_mut().push((id.into_u64(), handle, scope.frame)));
}

The first line is the cost of the integration when nobody is profiling: a load of the capturing flag and a branch. The name formatting happens at on_new_span, and Bevy creates a system span twice in a process's life, when the system is built and again when its schedule first initializes it, under the schedule's span; after that it is entered every frame and never recreated. A span that is created every frame (queue_submit count=3, whose field changes) is formatted every frame; that is the trade the layer makes rather than keep a cache keyed on fields.

Events ride along. info!, warn! and the rest become perfr log lines at the same level, formatted as target: message key=value. The one wrinkle is the log crate's bridge, which Bevy enables for its dependencies: a record from winit or wgpu arrives with the target log and its real origin in a log.target field. The layer takes that field as the target and drops the log.module_path, log.file and log.line siblings, so the line reads sctk_adwaita::buttons: button? and not log: button? log.target=... log.line=172.

What to call a span

A tracing span has a name and fields; a perfr scope has a name. The rule the layer settled on, after reading what Bevy puts where: the span's name, then a field called name after a colon with no key, then every other field as key=value. So schedule: Update, sub app: RenderApp, queue_submit count=3. The one exception is the span everyone looks for: a span named system is reduced to its name field alone, so a row reads bevy_render::view::window::prepare_windows and not system: bevy_render::view::window::prepare_windows nine hundred times a frame. The debug feature matters here; without it every system's name is <Enable the debug feature to see the name>.

One more thing about fields. info_span!("sub app", name = ?_label) records the label through Debug, which quotes strings, so the raw name would be sub app: "RenderApp". The layer strips a matched pair of quotes and nothing else. It is a small function with its own test, because it is exactly the kind of thing that looks wrong in a screenshot and nowhere else.

The frame that was not marked

Bevy does emit a frame boundary: an event with a tracy.frame_mark field, once a frame, after present. The layer turns that event into a frame instant. It also never saw one. The event is behind #[cfg(feature = "tracing-tracy")] in bevy_render, so an app that does not also compile the Tracy backend in has no frame mark at all, and LogPlugin has a filter to keep the event out of the formatted log that is equally conditional. A frame boundary is the one thing a profiler of a game cannot do without, so the layer grew frame_mark_on_exit("update"): a frame instant each time a scope with that exact name exits on the thread it ran on. update is the span SubApp::update puts around the whole of a frame's work on the main thread.

Why not the Main schedule, which is the frame in Bevy's own vocabulary? Because its span does not exist. tracing decides whether a span is enabled when the span is created, and a span created before any subscriber is installed is disabled for good. Schedule::new creates the schedule's span, and App::new() creates Main, PostUpdate and Last before any plugin runs, LogPlugin included. Those three schedules have no span in perfr, and none in Tracy either; their systems do, because a system recreates its span when its schedule first initializes it. The update span is created inside the run loop, after the subscriber, every frame. It is the right bracket for a reason that has nothing to do with perfr.

Godot: a fourth backend

Godot's seam is older in spirit and younger in code. Since 4.6, core/profiling/profiling.h defines a small vocabulary of macros and a SCons option, profiler=, that picks which backend they expand to. GodotProfileZone("name") is a scope to the end of the block. GodotProfileZoneGroupedFirst(group, "a") then GodotProfileZoneGrouped(group, "b") is a sequence of scopes that replace each other in one block, which is how the main loop reads:

GodotProfileZone("Main::iteration");
GodotProfileZoneGroupedFirst(_profile_zone, "prepare");
...
GodotProfileZoneGrouped(_profile_zone, "physics");
...
GodotProfileZoneGrouped(_profile_zone, "process");
...
GodotProfileZoneGrouped(_profile_zone, "RenderingServer::draw");

GodotProfileFrameMark is the frame. GodotProfileZoneScript and GodotProfileZoneScriptSystemCall are the GDScript VM's: one per script function call, one per call from a script into the engine. The header has a branch per backend and, at the bottom, a branch of empty stubs with a comment on each describing the contract, which is the specification a new backend is written against. Tracy, Perfetto and Instruments were the three. perfr is the fourth: an enum value in SConstruct, forty lines of SCons to find perfr.h (in profiler_path, then thirdparty/perfr/, then ~/.local/include/ where the installer puts it) and put its directory on the include path, and a branch in the header and the .cpp. Nothing is linked; perfr.h loads libperfr at run time if a perfr is installed and is a predictable branch per zone if not.

class Zone {
	perfr_scope handle = 0;
public:
	void begin(const char *p_name) { handle = perfr_start(p_name, strlen(p_name)); }
	void end() { if (handle) { perfr_stop(handle); handle = 0; } }
	void next(const char *p_name) { end(); begin(p_name); }
	explicit Zone(const char *p_name) { begin(p_name); }
	~Zone() { end(); }
};

#define GodotProfileZone(m_zone_name)                     godot_perfr::Zone GD_UNIQUE_NAME(__godot_perfr_szone_)(m_zone_name)
#define GodotProfileZoneGroupedFirst(m_group, m_zone_name) godot_perfr::Zone __godot_perfr_zone_##m_group(m_zone_name)
#define GodotProfileZoneGrouped(m_group, m_zone_name)      __godot_perfr_zone_##m_group.next(m_zone_name)
#define GodotProfileFrameMark                              godot_perfr::frame_mark()

The grouped macros are where the backends differ most, and the difference says something about the API underneath. Tracy's ScopedZone is an RAII object whose constructor is the start and whose destructor is the stop, so to replace a zone in place the Tracy backend has to call the destructor by hand and placement-new a fresh object into the same storage:

#define GodotProfileZoneGrouped(m_group_name, m_zone_name) \
	__godot_tracy_zone_##m_group_name.~ScopedZone(); \
	static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location, TracyLine){ ... }; \
	new (&__godot_tracy_zone_##m_group_name) tracy::ScopedZone(&TracyConcat(__tracy_source_location, TracyLine), true)

A perfr scope is a handle, an identity returned by perfr_start and consumed by perfr_stop, from any thread. Replacing one is end(); begin(name);, and the Zone class above is the whole backend for every non-script macro. The frame mark became a frame instant plus two value lanes, frame time (ms) and fps, read from the same Performance monitors the editor shows. The one piece of plumbing that is not pretty is startup: godot_init_profiler() runs before the OS singleton exists, so its one line of output, perfr: library loaded or perfr: no library found, goes through fprintf(stderr); the Unreal plugin logs the same one line through UE_LOG.

Naming a script call

The script macros are the Godot counterpart of Bevy's name problem, with a different constraint. Godot hands the backend StringNames: interned strings, compared by pointer, with the UTF-8 nowhere in reach without a conversion that allocates. Tracy's backend solves it by interning a SourceLocationData per call site, because Tracy wants a pointer that lives for the rest of the process. perfr wants the opposite: names travel in full with every event and are never interned, so a segment describes itself and a reader needs nothing but the segment. That means bytes, every call, from a string that is not stored as bytes.

Variant GDScriptFunction::call(...) {
	GodotProfileZoneScript(this, source, name, name, _initial_line);
	...
	// in the CALL opcodes:
	GodotProfileZoneScriptSystemCall(method, source, name, method->get_name(), line);

The backend caches the UTF-8 per call site in a thread-local HashMap keyed by the pointer the macro passes (this for a function, the MethodBind for an engine call), which is stable for the life of the script. The cache entry holds the StringNames it was built from, which keeps their data alive, which means the key pointer cannot be reused by another string while the entry exists; a hit still compares them, and a miss rebuilds. A function is named menu.gd:_process, the script file and the function. An engine call is named by the method, get_ticks_usec, nested in the script's scope. A call from one script function to another shows as both, the call site's work with the callee's main.gd:work inside it, because the VM opens the system-call zone before it knows what it is calling; the Tracy backend does the same, and Perfetto's goes to some trouble to suppress the inner one. Showing both is correct, if busy: the gap between them is the call overhead.

What arrived

Godot's third-person shooter demo, Forward+ on an RTX 4090, ten seconds at its menu, recorded by a second service so the one on the desk was not disturbed:

GET /api/functions/stats?pid=3518259&order=count&limit=100   (10 s at the demo's menu)

  OS_LinuxBSD::run                             413   avg 18.29 ms
    Main::iteration                            413   avg 18.27 ms
      physics                                  413   avg  0.02 ms
        Physics Step                           455   avg  0.02 ms      (physics ticks at 60 Hz, frames did not)
      process                                  413   avg  0.17 ms
        menu.gd:_process                       413   avg  0.01 ms
      RenderingServer::draw                    413   avg 18.05 ms
        viewport->draw_viewports               413   avg 15.59 ms
          rasterizer->blit_render_targets_to_screen  413   avg 14.52 ms
        rasterizer->end_frame                  413   avg  2.39 ms
          _begin_frame / _stall_for_frame / driver->fence_wait   413   avg 1.79 ms
      frame                                    413   (instant)

Sixty distinct zone names from one process, nested as the macros nest. The tree is also already a profile: 80% of the frame is inside blit_render_targets_to_screen, where the frame waits for the swapchain, because the demo requests full screen and the display is vsynced. The physics zones count 455 against 413 frames, since physics ticks at a fixed 60 Hz and this menu did not render at one. menu.gd:_process is a GDScript call every frame at thirteen microseconds.

From the Bevy side, the numbers in the guide: bevy_city at 44,800 entities and 1080p emits about 3,000 scopes a frame, some 900 of them system runs, 300,000 ring records a second at 30 fps, none dropped. The ring gives out past about a million records a second, which is why Bevy's detailed_trace feature, with its per-entity and per-archetype spans, is something to turn on for one system and not to run with.

Three engines, one shape

UnrealBevyGodot
The seamFExternalProfiler, a plugin registers oneLogPlugin::custom_layer, a tracing-subscriber layerprofiler=, a branch in core/profiling/
What becomes a scopeSCOPED_NAMED_EVENT, stat cycle counters, the engine's named eventsevery info_span! behind trace: systems, schedules, passesevery GodotProfileZone*: main loop, servers, RenderingDevice, GDScript calls
The frameFExternalProfiler::FrameSyncexit of the update span (the tracy.frame_mark event is Tracy-only)GodotProfileFrameMark, plus two lanes
Where names come fromUnreal ends an event without naming it: a per-thread stack of handlesspan name plus fields, formatted once per span creationliterals, or StringNames cached as UTF-8 per call site
Cost with no perfr presentone predictable branch per scope; nothing linked
Sizeone Core-only module291 lines, plus 59 in the example208 lines in five files
Chosen with-perfr -statnamedevents--features perfr (pulls bevy/trace, bevy/debug)scons profiler=perfr

The row that matters is the first. In all three the engine already had the concept of an external destination for its own instrumentation and a place to plug one in, and in all three that place was built for a different profiler. perfr's manual API was shaped so that fitting it there is small: a scope is a handle, a handle can be stopped from anywhere, a name is bytes with a length, and when no service is on the machine every call is one branch. The engines did the hard part years ago. The job was to notice.

The short version. Bevy and Godot both ship their own profiling instrumentation with a seam for an external backend; perfr now fits both. For Bevy, perfr-tracing is a tracing-subscriber layer that LogPlugin::custom_layer installs: spans become scopes named by the system's path, events become log lines, and the exit of the update span marks the frame, since Bevy's own frame mark is compiled in only with Tracy. For Godot, profiler=perfr is a fourth backend of the GodotProfile* macros: grouped zones are a stop and a start on a handle, GDScript calls are named file.gd:function from a per-site UTF-8 cache, and the frame mark adds two lanes. Neither engine gained a line of instrumentation; both gained a destination.