Performance
Most CUDA kernels are slow for one of three reasons: they read memory badly, they cannot keep enough warps resident, or they are doing work that does not need to happen. This chapter is how to tell which one you have.
First question: memory-bound or compute-bound?#
Every kernel moves some bytes and performs some floating-point operations. The ratio is arithmetic intensity, in flops per byte:
| Kernel | Intensity | Usually limited by |
|---|---|---|
c[i] = a[i] + b[i] | ~0.08 flop/byte | Memory bandwidth |
| 3×3 convolution | ~1–2 flop/byte | Memory bandwidth |
| Dense matrix multiply | ~20–100 flop/byte | Compute (or tensor cores) |
| Small reduction | ~0.02 flop/byte | Memory bandwidth |
Modern GPUs have roughly 10–100 flops of compute per byte of DRAM bandwidth. Below that balance point, making the arithmetic faster changes nothing; you have to move fewer bytes.
Coalescing#
Global memory is served in 32-byte transactions. A warp's 32 lanes each request 4 bytes; if those 128 bytes are contiguous, the hardware fetches four 32-byte sectors and every byte is used. If the lanes are spread out, each lane may pull its own sector and 7/8 of the fetched bytes are wasted.
The widget shows a warp of 32 threads loading one float each. With stride 1, four transactions cover all 128 bytes — 100% efficiency. With stride 8, each lane lands in its own 32-byte sector: 1,024 bytes fetched for 128 bytes used, 12.5% efficiency.
The rule: consecutive lanes should touch consecutive addresses.
The classic mistake: arrays of structs#
struct Particle { float x, y, z; };
__global__ void readX(const Particle* p, float* out, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = p[i].x; // lanes are 12 bytes apart
}Each lane reads 4 bytes from a 12-byte-strided array. A warp touches 384 bytes spread over 12 sectors to use 128 bytes. The fix is structure-of-arrays:
struct Particles { float* x; float* y; float* z; };
__global__ void readX(const Particles p, float* out, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = p.x[i]; // lanes are 4 bytes apart: coalesced
}Same data, same arithmetic, three times less memory traffic for this access pattern.
Vector loads#
If each thread needs four consecutive floats, load a float4 instead of four separate floats:
float4 v = reinterpret_cast<const float4*>(in)[i];
out[i] = v.x + v.y + v.z + v.w;This issues one 16-byte load per thread and fully uses the 32-byte sectors. It requires 16-byte alignment (cudaMalloc gives at least 256-byte alignment), and it changes the indexing: i now counts float4s, not floats.
Occupancy#
Occupancy is the fraction of an SM's maximum warps that are actually resident:
occupancy = active warps per SM / maximum warps per SMAn SM might support 64 warps (2,048 threads). If your block has 256 threads and only four blocks fit, you have 32 warps resident: 50% occupancy.
Three resources limit how many blocks fit:
- Threads per SM — usually 2,048.
- Registers per SM — usually 65,536; each thread's registers are multiplied by the block size.
- Shared memory per SM — tens to hundreds of KB, shared among resident blocks.
The widget uses representative limits (2,048 threads, 65,536 registers, 100 KB shared). Push registers to 128 per thread and watch the register limit take over; push shared memory to 48 KB and watch that become the cap.
Asking the runtime#
int blocks_per_sm = 0;
cudaOccupancyMaxActiveBlocksPerMultiprocessor(
&blocks_per_sm, kernel, 256, 0);
int sms = 0;
cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, 0);
printf("%d blocks/SM -> %d warps/SM (max grid %d blocks)\n",
blocks_per_sm, blocks_per_sm * 256 / 32, blocks_per_sm * sms);This is the authoritative answer for your kernel on your GPU; the widget is a model. Use the API when sizing a persistent grid or a cooperative launch.
More occupancy is not always faster#
High occupancy hides memory latency, but it is not a goal by itself:
- A kernel with enough instruction-level parallelism can saturate memory at 25% occupancy.
- Forcing occupancy down with
__launch_bounds__can give each thread more registers and avoid spills. - Some kernels (small matmuls, stencils) run best at moderate occupancy.
Measure. If a kernel is at 100% occupancy and still slow, occupancy was never the problem.
Arithmetic and instruction mix#
When memory is not the bottleneck:
- Divergence splits warps into serial passes (Chapter 5). Reorder work so lanes agree.
- Special functions (
sinf,expf,powf) run on a small SFU and are much slower than adds. Use__expf/__sinffast-math variants when precision allows. - 64-bit arithmetic is slower than 32-bit on many GPUs. Use
intandfloatunless you need the range. - Integer division and modulo are expensive. Replace with bit operations when the divisor is a power of two.
- Register spills show up as local memory traffic. Check
-Xptxas -v.
Profile, do not guess#
Nsight Compute gives per-kernel counters:
$ ncu --set full ./app
$ ncu --metrics gpu__time_duration.sum,dram__bytes_read.sum,\
l1tex__t_sectors_pipe_lsu_mem_global_op_ld.sum ./appNsight Systems shows the timeline: copies, kernels, gaps, and stream overlap.
$ nsys profile --stats=true ./appWhat to look at, in order:
- Duration — is this kernel actually the problem?
- Memory throughput —
% of peakfor DRAM. Above ~70% means you are near the roof. - Compute throughput — if both memory and compute are low, you are latency-bound (not enough warps).
- Achieved occupancy — compare with theoretical.
- Sectors per request — for loads, 4.0 is perfect for 32-byte sectors; much higher means uncoalesced access.
- Warp stall reasons — long scoreboard (memory), barrier, branch, not-selected.
A tuning checklist#
| Symptom | Likely cause | Fix |
|---|---|---|
| Low DRAM throughput, high sectors/request | Uncoalesced access | Reorder data, SoA, transpose |
| Low DRAM throughput, low occupancy | Too few warps | Smaller blocks, fewer registers, less shared memory |
| High shared-memory bank conflicts | Stride aligned to 32 banks | Pad the array |
| Warp divergence stalls | Data-dependent branches | Sort/bucket, predication, restructure |
| Low compute utilisation, high memory | Memory-bound | Reduce bytes, fuse kernels, cache in shared |
| Gaps between kernels | Launch overhead / sync | Streams, graphs, batch work |
| Copies dominate | PCIe transfers | Keep data on device, overlap with streams |
A worked example#
Take the tiled matrix multiply from Chapter 8. Three measurements tell you where you stand:
- DRAM bytes: ideally
3 × N² × 4bytes (read A, read B, write C), plus tile re-reads. - Achieved occupancy: with 16×16 blocks and 2 KB shared, usually high.
- Tensor-core utilisation: zero, because the kernel uses plain FP32 multiply-add.
For large matrices, the next step is not a bigger tile — it is using tensor cores (wmma or the tile API in Chapter 14), which changes the compute roof by an order of magnitude.
Exercises#
- In the coalescing widget, find a stride where efficiency is exactly 50%. How many 32-byte sectors does the warp touch?
- Rewrite the
Particlekernel with structure-of-arrays and estimate the traffic reduction forreadX. - Use
cudaOccupancyMaxActiveBlocksPerMultiprocessoron three kernels with different register counts. Compare the predicted warps withncu's achieved occupancy. - Profile the tiled matmul with
ncu --set full. What is the limiting factor: DRAM, compute, or latency? - Why can a kernel at 25% occupancy still saturate memory bandwidth? What must be true about each thread's instruction stream?