Culling and the frame
GPU timing and frame statistics
To make a renderer faster, you first need to know where the time goes and how much work the GPU really did. That is harder than it sounds: the GPU runs later than the CPU, on its own clock, and its results come back frames later. This page explains how engines measure GPU time and count GPU work without slowing the frame down. The last part shows how RASM does it.
In short
- The CPU records commands; the GPU runs them later. A CPU timer around a draw call measures the recording, not the drawing.
- A timestamp query asks the GPU to write its own clock into a query pool when it reaches a point in the command stream. Two timestamps give the time of the work between them.
- Ticks become nanoseconds with the timestamp period. Only the low valid bits count, so the difference must be taken modulo 2bits.
- Results are read after the frame's fence, so they arrive N frames late (N = frames in flight), and the CPU never waits for them.
- Shaders can count their own work (objects culled, triangles kept) with atomics into a small buffer that the CPU reads the same way. A 64-bit count can be built from 32-bit atomics with a carry.
- Single-frame numbers are noisy: average them, or refresh the text slowly, so that people can read them.
1Two clocks: CPU time and GPU time
A frame has two kinds of time. CPU time is how long the CPU works on the frame: game logic, culling, recording command buffers. GPU time is how long the GPU works on it: running the shaders, writing pixels. The two run at the same time, on different frames.
GPU-bound
The GPU is the slower one, and the CPU ends up waiting. Making the CPU faster would change nothing.
CPU-bound
The CPU is the slower one. The GPU sits idle between frames.
The time from one frame start to the next is the frame time. It is easy to measure on the CPU, and it is what the player feels. But it is neither the CPU time nor the GPU time: it is the larger of the two, plus any waiting. With vertical sync on, it is also rounded up to the display's refresh interval (16.7 ms at 60 Hz), even if both sides finish in 3 ms.
2Why the CPU cannot time GPU work
The obvious idea fails: start a CPU timer before a draw call and stop it after. The draw call only writes a command into a command buffer. It returns in microseconds, long before the GPU starts it. Waiting for the GPU does not work either:
Timer around the draw call
Really measures: the cost of recording the command.
Timer from submit to "the fence is signalled"
Really measures: the GPU work plus the queue wait (earlier frames still running), the driver's delay, and the moment the CPU noticed the fence.
Submit each pass alone and wait for it
Really measures: the pass, but the GPU now idles between passes and cannot overlap them. The frame becomes much slower, and the numbers describe that slower frame.
The only reliable clock for GPU work is the GPU's own clock. The GPU must write it down at the right moments, while it runs the frame as usual.
3Timestamp queries
A query is a small slot that the GPU fills with an answer. A query pool is an array of them. A timestamp query is filled with the value of the GPU's clock. The command that fills it goes into the command buffer, between other commands, like a bookmark:
What the API tells you about the clock
| Value (Vulkan name) | Meaning | Use |
|---|---|---|
| Timestamp period (timestampPeriod) | nanoseconds per tick, a float. Often 1, but it can be 10, 41.7, 52.1, … depending on the GPU. | ns = ticks × period |
| Valid bits (timestampValidBits, per queue family) | how many low bits of the 64-bit value are real. 0 means the queue has no timestamps. | take differences modulo 2bits (below) |
| Pipeline stage of the write | the timestamp is written once all earlier commands have finished that stage | use "all commands" (or "bottom of pipe") to mean "everything before is done" |
Wrap-around
With fewer than 64 valid bits, the counter wraps back to 0 now and then. A pass that straddles the wrap has an end timestamp smaller than its begin. Plain subtraction then gives a huge number. The fix is to subtract and keep only the valid bits; that is subtraction modulo 2bits:
mask = 2^bits − 1 bits = 32 → mask = 0xFFFFFFFF
ticks = (end − begin) & mask
begin = 0xFFFFF000 end = 0x00001000 (the counter wrapped in between)
ticks = 0x00001000 − 0xFFFFF000 = 0x2000 (mod 2^32) = 8192 ticks
→ 8192 × 40 ns = 0.328 ms
This works as long as the measured work is shorter than one full turn of the counter. Even with 32 bits and a 1 ns tick, a turn is 4.3 seconds.
Rules of query pools
- Reset before use.A query must be reset before the GPU writes it again, either by a command in a command buffer or, where supported, from the CPU (Vulkan 1.2 "host query reset").
- Read after the GPU is done.Reading earlier either fails ("not ready") or, with a "wait" flag, blocks the CPU until the GPU gets there.
- Do not reuse while in flight.A pool that the GPU is still writing cannot be reset by the CPU. With several frames in flight, each frame needs its own pool (section 4).
4Reading results without stalling
The timestamps of frame N are written while the GPU runs frame N, which is after the CPU has moved on. If the CPU waited for them right away, it would lose the overlap of section 1. Instead, each frame-in-flight slot gets its own query pool. The CPU reads a slot's pool at the moment it must wait for that slot anyway: after the slot's fence, just before it records the slot's next frame.
Step through it. Each frame reads the pool of its own slot, which an older frame wrote.
The same pattern works for anything the GPU writes for the CPU: counters (section 7), readback of pixels, GPU-generated lists. A frame that was recorded but never submitted wrote nothing, so the reader must notice that (for example, by checking that the fence value moved) and skip the slot.
5Per-pass timers
A timer is a pair of timestamps: one before a piece of work, one after it. Put a pair around the whole frame and one around each pass, and you have a profile of the frame. A pool with 2k queries holds k timers: timer i uses query 2i for its begin and 2i + 1 for its end.
Pass times do not add up to the frame time
A GPU overlaps work: the next pass may start before the previous one has fully drained. Nested timers are counted twice if added.
Timestamps are cheap, not free
A timestamp waits for earlier work to reach its stage. Many timers inside a pass can reduce overlap a little. A few per pass are fine.
Tile-based GPUs (most phones)
Inside a render pass, the GPU works tile by tile, not draw by draw. Timestamps between draws in one pass are not meaningful there; time whole passes.
Clock speed changes
A GPU with little work lowers its clock. A light frame can then show longer times than expected. Profile with a stable workload, or ask the driver for a stable clock.
Fixed pool size
A pool holds a fixed number of timers. When a frame wants more, the extra ones must be dropped, ideally with one warning, not one per frame.
6Pipeline statistics, and other counters
Timestamps say how long. Other questions are "how much": how many vertices, triangles or pixels did the GPU really process? APIs have query types for that too:
Pipeline statistics
Counts per pipeline stage: input vertices and primitives, vertex shader runs, primitives after clipping, fragment shader runs, compute shader runs. Chosen by flags when the pool is made.
Occlusion
Counts samples that passed the depth test between begin and end. Used for occlusion tests and lens flares.
Vendor counters
Cache hits, memory traffic, occupancy. Seen in tools like Nsight, Radeon GPU Profiler or PIX, not usually inside the engine.
Pipeline statistics have the same timing as timestamps (begin, end, read frames later). They are optional on some hardware and have a small cost. They cannot answer questions about the engine's own work, such as "how many objects did culling keep?". For that, the shaders count by themselves.
7Counting in shaders, with atomics
In a GPU-driven renderer the GPU decides what to draw, so the CPU does not know how many objects survived culling or how many triangles were drawn. The shader that decides can count. Thousands of threads add to the same counter, so the add must be an atomic operation: a read-modify-write that no other thread can interrupt.
64-bit counts from 32-bit atomics
A 32-bit counter overflows at 4,294,967,295. A big scene can draw more triangles than that per frame. 64-bit atomics would fix it, but not every GPU and API has them: WebGPU has none, and Metal has them only on some GPUs and only for some operations. The trick: keep two 32-bit words, low and high, and carry by hand.
1. Add up a group's numbers in 64 bits
Unsigned 32-bit math wraps around, it does not fail. So "the result went down" means "it passed 232". This part has no atomics: one thread owns these two words.
2. Add the group's total to the buffer
The atomic returns the value from just before this group's add. Only this group's add can have caused the wrap it sees, so each carry is counted exactly once.
3. Read it on the CPU
Reading in the middle of the frame could see a low word that has wrapped and a high word that has not been incremented yet. Reading after the fence avoids that.
8Turning numbers into something readable
A frame time changes every frame by a little, and sometimes by a lot (a spike). Printing every frame's value makes an unreadable blur. Common fixes:
Sample and hold
Show the latest value, but update the text only a few times per second.
The simplest; readable; hides spikes between updates
Mean over a window
Keep the last n values in a ring, show their average.
Steady numbers; needs memory for n values
Exponential moving average
avg = avg + α · (value − avg), with α = 0.05 to 0.2.
One number of state; reacts in about 1/α frames
Max, or percentiles
The worst frame of the last second; the 99th percentile ("1% low" fps).
Stutter: the average hides it, the max shows it
A graph
A strip of the last few hundred frame times.
Seeing spikes and patterns at a glance
An example with α = 0.1. Frames take 16.7 ms, then one takes 40 ms, then 16.7 ms again:
The spike is visible, but it does not take over the display.
Try the four methods on the same frames: 16.7 ms with some noise, and one frame of 40 ms.
Frame rate is 1000 / ms, which is not linear. Two frames of 10 ms and 30 ms average 20 ms, which is 50 fps. Averaging their rates (100 fps and 33 fps) gives 67 fps, which is wrong. Average the times, then convert.
9Measure only when someone looks
Timers, counters and readback are cheap but not free: a few commands per pass, some atomics in the shaders, a buffer read and a text update per frame. A common rule is to measure only while an overlay is shown or a tool asks for the numbers. Two details follow:
- The first values arrive N frames after measuring starts (section 4). Until then, show zeros or nothing.
- A counter that the shaders always add to (because skipping the atomics would need a shader branch) must be zeroed before the first measured frame, or it shows garbage from earlier frames.
10Memory numbers
The other number people ask for is "how much video memory do we use?". The API can tell, per memory heap:
| Number | Meaning |
|---|---|
| Budget | how much of this heap the process can use now without trouble. It changes with what other programs use. Going over it makes the driver move memory around, which is slow. |
| Usage | how much of this heap the process uses now, counting everything: buffers, textures, the swapchain, the driver's own allocations. |
| Heap size | the total. It never changes, and it is not what you can really use. |
In Vulkan these come from the VK_EXT_memory_budget extension. A heap marked device-local is video memory on a discrete GPU. On an integrated GPU, or with resizable BAR, device-local memory can also be visible to the CPU, so "device-local" and "video memory" are not exactly the same thing. See GPU memory.
11In RASM
RASM collects one set of numbers per frame into a public FrameStats. The application reads it with Renderer::getFrameStats; the stats overlay draws it on screen. Everything follows sections 3 to 9: timestamp pairs per pass, one query pool and one counter buffer per frame slot, read after the slot's fence.
updateFrameStats fills FrameStats once per frame, right after the fence wait of the frame's slot s. cpuFrameMs and memory are current; the GPU numbers belong to the slot's previous frame, two frames ago.The timers
Each slot has a pool of 2 × MAX_GPU_TIMERS = 512 timestamps, so 256 timers. Timer i writes queries 2i and 2i + 1, both with vkCmdWriteTimestamp2 at the "all commands" stage.
| Timer | Started by | Name |
|---|---|---|
| The frame on the graphics queue | beginFrame, ended in endFrame | "Frame" (always timer 0, not listed) |
| Each graphics pass | beginPass / endPass | the pass name: "Scene 1" and "Scene 2" of the scene passes ("Scene" without occlusion culling), "Tone Map", "Clear" for the empty swapchain pass, or your graph pass's name |
| Each render graph compute pass, on its queue | RenderGraph::execute | the pass name: "Cull 1", "Hi-Z" and "Cull 2" of the scene passes ("Cull" without occlusion culling), or your graph pass's name |
| The application's own work | Renderer::beginGpuTimer / Renderer::endGpuTimer | its own name |
Without async compute every timer is in the frame's one command buffer, around one pass. With EngineConfig::asyncCompute, a timer is in the batch of its pass's queue. It begins and ends on that queue, so its own time holds. gpuFrameMs runs from the "Frame" timer's start to the latest end of a graphics-queue timer. Compute-queue timers are left out of it: timestamps of two queues may not count from the same origin (section 3). So each compute timer's time is read from its own two queries, never measured against a graphics one. gpuTimers are listed in the order they were recorded, which is the order each queue runs them: "Cull 1", "Scene 1", "Hi-Z", "Cull 2", "Scene 2".
VulkanDevice::getTimestamps reads count queries from firstQuery and turns them into nanoseconds since the first of them: each value becomes its distance from the first one, masked to timestampValidBits (the wrap rule of section 3). A distance in the upper half of that range is before the first and reads 0; the rest is multiplied by timestampPeriod and clamped, since a query of the other queue may be far off. updateFrameStats reads all queries from query 0, the "Frame" timer's begin, and each compute timer again on its own. It reads without the wait flag, so a pool that is not ready returns nothing instead of stalling.
The counters
The cull shader counts what it keeps. Each slot has a Cull Stats Buffer of CULL_STATS_WORDS = 22 words, host-visible and host-readable. The STATS_* constants in cull.slang and glyphCull.slang and the CULL_STATS_* ones in gpuScene.h name them:
| Words | Holds | Becomes |
|---|---|---|
| [0] | visible draws | drawsVisible |
| [1] low, [2] high | visible triangles at the LOD culling picked | trianglesVisible |
| [3] low, [4] high | the same draws' triangles at LOD 0 | trianglesVisibleLod0 |
| [5] … [12] | visible draws at LOD 0 … 7 | drawsPerLod |
| [13], [14] | lights in the clusters, lights dropped | lightsVisible, lightsDropped |
| [15], [16], [17] | meshlets drawn, meshlets culled, draws over the meshlet budget | meshletsVisible, meshletsCulled, meshletDrawsWhole |
| [18] low, [19] high | the visible draws' triangles at their LOD, before meshlet culling | trianglesVisibleLod |
| [20], [21] | glyphs tested, glyphs drawn (the glyph cull; their triangles go to [1], [2]) | glyphs, glyphsVisible |
countMain does what section 7 describes. Each thread writes its result to shared memory; the group's last thread adds the 64 triangle counts in two words with a carry, then calls InterlockedAdd once for the draw count and addCount64 for each triangle count. Threads 0 to 7 each count the group's draws at their LOD and add that. The early and the late culling (see occlusion culling) both count, and a draw is still counted once, because the late pass only keeps draws the early one did not draw. Draws of a scene view drawn without culling are not seen by the shader, so the CPU adds them from DrawTotals (unculledDraws, unculledTriangles), counted at LOD 0.
MAX_FRAMES_IN_FLIGHT is 2, so the GPU numbers are two frames old. endFrame records one COMPUTE → HOST barrier after the last pass, or with async compute submitBatches records it at the end of the last compute batch, where the culling ran, so the CPU sees the counters once the fences are reached.Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| "CPU" time | the CPU's work on a frame | cpuFrameMs is frameTime × 1000: the frame time, from one frame start to the next, capped at 100 ms, measured even with EngineConfig::fixedDeltaTime. With the FIFO present mode (B21) it is held at the display's refresh interval. CPU work time per zone is measured with Tracy instead (D16). |
| Timestamps | pairs, period, valid bits | The same: one pool per frame slot, 256 timers, wrap-safe conversion. Compute passes next to each other with one Pass::timerName share a timer: the 11 bloom passes are one, Bloom. |
| Reading | after the slot's fence, no wait | The same, in updateFrameStats. A slot whose fence value did not move (a frame that was not submitted) is skipped. |
| Reset | by command or from the host | From the host (vkResetQueryPool, host query reset), right after the read. |
| Frame GPU time | earliest begin to latest end | From the "Frame" timer's start to the latest end on the graphics queue. With one queue that is the same. With async compute, the compute-queue timers are left out, since timestamps of two queues may not share a clock. |
| Timer order | by start time | The order they were recorded, which is the order each queue runs them. |
| Too many timers | drop, warn once | The same: one warning per run. |
| Pipeline statistics | optional queries | None. |
| Shader counters | reduce in the group, one atomic | The same, in countMain: one atomic per group per counter, plus up to 8 for the LOD counts. |
| 64-bit counts | two words and a carry | The same, in addCount64; the CPU joins them in readCount64. |
| Smoothing | average, EMA, max, graph | None. FrameStats holds one frame's values. The overlay uses sample and hold: it rebuilds its text every 0.25 s of frame time, the sum of deltaTime, so with EngineConfig::fixedDeltaTime the same frames show in every run (C15). |
| Measure on demand | only while someone looks | A slot is measured while showStats is on (F1), or for good once getFrameStats has been called. Otherwise no timestamps are written and nothing is read; only cpuFrameMs updates. The cull shader always adds to its counters; they are zeroed before each measured frame. |
| Memory | budget and usage per heap | queryVRAMStats adds up the device-local heaps into vramBudget and vramUsage (whole blocks), and VMA's allocation bytes in them into vramAllocated, and the other heaps into hostBudget and hostUsage (VRAMStats). Read every measured frame. |
| No timestamp support | valid bits = 0 | The pool is not created (with a warning). The stats then have no GPU times; the rest still works. |
Where it lives in code
| What | Where |
|---|---|
| Public types | FrameStats, GpuTimer, MAX_GPU_TIMERS in include/rasm/renderer.h; VRAMStats in include/rasm/render/resource.h |
| Per-slot state | FrameStatsSlot, FrameStatsCollector in src/renderer/frameStats.h |
| Timers, read-back, reset | Renderer::updateFrameStats, Renderer::beginGpuTimer, Renderer::endGpuTimer, Renderer::getFrameStats in src/renderer/frameStats.cpp |
| Frame and pass timers | Renderer::beginFrame, Renderer::endFrame, Renderer::beginPass, Renderer::endPass in src/renderer/renderer.cpp; RenderGraph::execute in src/renderer/renderGraph.cpp |
| Query pool, timestamps, VRAM | VulkanDevice::createTimestampQueryPool, VulkanDevice::getTimestamps, VulkanDevice::queryVRAMStats in src/rhi/vulkan/vulkanDevice.cpp; VulkanCommandBuffer::writeTimestamp in src/rhi/vulkan/vulkanCommandBuffer.cpp |
| Counters and draw totals | DrawTotals, cullStats, CULL_STATS_WORDS in src/renderer/gpuScene.h; countMain, addCount64 in shaders/passes/cull.slang |
frameTime, deltaTime, F1 | Renderer::pollEvents in src/renderer/renderer.cpp, the SDL events in src/platform/sdlPlatform.cpp |
- The
STATS_*words incull.slangmatch theCULL_STATS_*words ingpuScene.h. - A slot's pool and counter buffer are read and reset only after that slot's fence wait (the frame order in
beginFrame). endFramerecords aCOMPUTE → HOSTbarrier after the last pass, or with async computeRenderer::submitBatchesone at the end of the last compute batch; without it the CPU may read stale counters.- Only timers on the graphics queue count toward
gpuFrameMs. A timer begins and ends on one queue. beginGpuTimermay returnUINT32_MAX;endGpuTimermust accept it and do nothing.
The GPU timers do not reach Tracy, and Tracy cannot be turned off (D16). There are no pipeline statistics and no averaging or frame-time graph.
Further reading
- The Vulkan specification: the chapter "Queries", in particular "Timestamp Queries" and "Pipeline Statistics Queries", and the VK_EXT_memory_budget extension.
- The Khronos Vulkan Samples: the "timestamp queries" sample.
- Tomas Akenine-Möller and others, Real-Time Rendering, 4th edition: the chapter on pipeline optimization (finding the bottleneck).
- Bartosz Taudul, Tracy Profiler manual: CPU zones and GPU zones.