Profiling: Scopes and Tracy
At 60 FPS a frame has 16.67 ms; at 120 FPS, 8.33 ms. Those numbers are the whole budget: input, gameplay, physics, animation, audio submission, culling, command recording and the GPU's work all have to fit (the CPU and GPU run in parallel, so each must fit). When a frame takes 22 ms, the only useful question is "where did the time go?", and the only reliable answer comes from a profiler.
Engines use two complementary kinds:
| Kind | How | Good at |
|---|---|---|
| Sampling (perf, Visual Studio, Superluminal, VTune) | interrupts the program thousands of times a second and records the call stack | finding hot functions with no code changes |
| Instrumentation (Tracy, Optick, Unreal Insights, your own scopes) | named zones you put in the code, timed on enter and exit | frame-by-frame timelines, spikes, threads, waits |
Spikes, the frame that took 40 ms once every few seconds, are where instrumentation shines: a sampling profiler averages them away.
A scope profiler, modelled
An instrumented zone is an RAII object: its constructor records the start time and pushes the zone onto a per-thread stack, its destructor records the end time and pops it. The stack gives the hierarchy; the times give total (including children) and self (excluding children) durations.
Real profilers read a hardware clock. Here the clock is simulated: each piece of fake work advances a tick counter (1 tick = 0.01 ms), so the report is identical on every run.
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
struct SimClock {
long ticks = 0; // 1 tick = 0.01 ms
void work(long t) { ticks += t; }
};
SimClock gClock;
struct ZoneRecord { std::string name; int depth; long start, end, childTicks; };
class Profiler {
public:
std::vector<ZoneRecord> zones;
std::vector<int> stack;
int begin(const std::string& name) {
zones.push_back({name, int(stack.size()), gClock.ticks, 0, 0});
stack.push_back(int(zones.size()) - 1);
return stack.back();
}
void end(int idx) {
stack.pop_back();
zones[idx].end = gClock.ticks;
if (!stack.empty()) zones[stack.back()].childTicks += zones[idx].end - zones[idx].start;
}
void report(double budgetMs) {
std::cout << std::fixed << std::setprecision(2);
for (auto& z : zones) {
double total = (z.end - z.start) / 100.0, self = (z.end - z.start - z.childTicks) / 100.0;
std::cout << std::string(z.depth * 2, ' ') << std::left << std::setw(18 - z.depth * 2) << z.name
<< std::right << std::setw(7) << total << " ms total" << std::setw(7) << self << " ms self\n";
}
double frame = (zones[0].end - zones[0].start) / 100.0;
std::cout << "frame " << frame << " ms of " << budgetMs << " ms budget: ";
if (frame <= budgetMs) std::cout << "OK\n";
else std::cout << "OVER by " << frame - budgetMs << " ms\n";
zones.clear();
}
};
Profiler gProfiler;
struct Zone { // what ZoneScopedN("...") expands to, roughly
int idx;
explicit Zone(const char* name) : idx(gProfiler.begin(name)) {}
~Zone() { gProfiler.end(idx); }
};
void updateAI(int enemies) { Zone z("AI"); gClock.work(enemies * 3); }
void pathfinding(int queries){ Zone z("Pathfinding"); gClock.work(queries * 40); }
void physics() { Zone z("Physics"); gClock.work(180); }
void gameplay(int enemies, int queries) {
Zone z("Gameplay");
gClock.work(50); // gameplay's own work
updateAI(enemies);
pathfinding(queries);
}
void render() { Zone z("Render"); { Zone c("Cull"); gClock.work(120); } { Zone r("Record"); gClock.work(310); } }
void frame(int enemies, int queries) {
Zone z("Frame");
gameplay(enemies, queries);
physics();
render();
}
int main() {
const double budget = 16.67;
std::cout << "--- normal frame ---\n";
frame(100, 2);
gProfiler.report(budget);
std::cout << "--- spike frame: 25 path queries at once ---\n";
frame(100, 25);
gProfiler.report(budget);
}--- normal frame ---
Frame 10.40 ms total 0.00 ms self
Gameplay 4.30 ms total 0.50 ms self
AI 3.00 ms total 3.00 ms self
Pathfinding 0.80 ms total 0.80 ms self
Physics 1.80 ms total 1.80 ms self
Render 4.30 ms total 0.00 ms self
Cull 1.20 ms total 1.20 ms self
Record 3.10 ms total 3.10 ms self
frame 10.40 ms of 16.67 ms budget: OK
--- spike frame: 25 path queries at once ---
Frame 19.60 ms total 0.00 ms self
Gameplay 13.50 ms total 0.50 ms self
AI 3.00 ms total 3.00 ms self
Pathfinding 10.00 ms total 10.00 ms self
Physics 1.80 ms total 1.80 ms self
Render 4.30 ms total 0.00 ms self
Cull 1.20 ms total 1.20 ms self
Record 3.10 ms total 3.10 ms self
frame 19.60 ms of 16.67 ms budget: OVER by 2.93 ms
The normal frame takes 10.40 ms and fits easily. The spike frame takes 19.60 ms, 2.93 ms over budget. Gameplay jumped from 4.30 to 13.50 ms, and drilling down shows its self time unchanged while Pathfinding exploded: 25 queries in one frame. The fix is not a faster A*; it is a budget of, say, four path queries per frame with the rest queued, which is exactly the kind of answer a profiler leads you to.
Tracy
Tracy (Bartosz Taudul, BSD-3) is the de facto open-source frame profiler for C++ engines: nanosecond-resolution zones, multiple threads on one timeline, locks, memory allocations, plots, messages, GPU zones for OpenGL, Vulkan, D3D11/12 and Metal, and frame images. The client is a library you link; the viewer (tracy-profiler) connects over the network, live or to a saved trace.
#include <tracy/Tracy.hpp>
void Physics::step(float dt) {
ZoneScoped; // zone named after the function
{
ZoneScopedN("Broadphase"); // explicitly named zone
broadphase.update();
}
ZoneScopedN("Solve");
ZoneValue(contacts.size()); // attach a number to this zone
solver.solve(dt);
}
void Game::frame() {
update();
render();
TracyPlot("Enemies", int64_t(enemies.size())); // a graph over time
FrameMark; // marks the end of a frame
}
void* operator new(std::size_t n) { void* p = std::malloc(n); TracyAlloc(p, n); return p; }
void operator delete(void* p) noexcept { TracyFree(p); std::free(p); }
TracyLockable(std::mutex, jobQueueMutex); // shows lock contention on the timelineSetup notes:
- All macros compile to nothing unless
TRACY_ENABLEis defined, so zones can stay in the code permanently. With CMake, Tracy's ownTRACY_ENABLEoption puts the define on theTracyClienttarget. Upstream turned that option off by default in 0.14, so pass-DTRACY_ENABLE=ONwhen you add Tracy as a subdirectory or with FetchContent; vcpkg'stracyport builds with it on and gives youfind_package(Tracy CONFIG REQUIRED)andTracy::TracyClient. - The client and viewer protocol must match: build the viewer from the same Tracy version as the client library (vcpkg's port has a
gui-toolsfeature, or use the release binaries for Windows). TRACY_ON_DEMANDmakes the client collect data only while a viewer is connected, useful for builds you hand to testers.- GPU zones need the backend header (
tracy/TracyOpenGL.hpp:TracyGpuContext,TracyGpuZone("Shadows"), andTracyGpuCollectafter swapping buffers;tracy/TracyVulkan.hppfor Vulkan).
Habits that make profiling work
- Profile optimised builds (
RelWithDebInfo), on the target hardware. A debug build's hot spots are not the release build's hot spots. - Look at the worst frames, not the average. Tracy's "find zone" histogram shows the distribution; players feel the 99th percentile.
- Zones are cheap but not free (roughly tens of nanoseconds each in Tracy). Don't put one inside a loop that runs a million times; zone the loop.
- Record before and after every optimisation, with the same scene and camera path. If the number didn't move, revert the clever code.
- Check the GPU separately with RenderDoc, PIX, Nsight Graphics or Radeon GPU Profiler: a CPU timeline that waits in
SwapBuffersorvkQueuePresentKHRusually means you are GPU-bound.
The tools themselves are listed in Toolkit: Debuggers, Sanitizers and Profilers.
Test yourself
In a hierarchical profile, what is a zone's 'self' time?
- Its time on the first frame
- Its total time minus the time spent in its child zones
- The time spent by other threads
- Its average time
Why are instrumentation profilers like Tracy especially good for frame spikes?
- They use less memory
- They record every frame on a timeline, so one slow frame can be inspected instead of being averaged away
- They sample more often
- They only run on the GPU
What happens to ZoneScoped and FrameMark when TRACY_ENABLE is not defined?
- Compile error
- They expand to nothing, so the code costs nothing
- They log to stdout
- They still collect data but don't send it