The Complete Guide to CUDA Performance Optimisation
A working method for faster CUDA kernels: classify the bottleneck, fix memory access, tune occupancy and divergence, overlap transfers and verify each change.

A slow CUDA kernel is almost never slow for the reason its author guesses. People rewrite arithmetic that was never the limit, raise occupancy that was already enough, or unroll a loop whose cost was a memory stall three lines above it. The cure is a method: decide what the kernel is limited by, change one thing that addresses that limit, and measure again. This guide gives that method and then works through the techniques in the order they usually pay off, using CUDA 12.9, with code for each and a complete worked example at the end. It assumes you can already write a kernel and launch it, as covered in the grid and block size post and the memory types post, and it points to the focused posts in this cluster for each tool. Every architectural statement comes from the NVIDIA CUDA C++ Best Practices Guide and the CUDA programming guide, and where we give a number it is computed from the code shown, never measured on a particular card.
The rule that governs everything: measure first
Optimizing without a measurement is guessing with extra steps. Before you change a line, you need two things: a timing you trust and a classification of the bottleneck. The timing comes from CUDA events around the kernel, or better from Nsight Systems for a whole application, because the runtime of one kernel says nothing about whether the program spends its time in kernels at all. The classification comes from Nsight Compute, which reports how close the kernel is to the peak of each hardware unit.
Here is the loop to repeat for every change:
Time the whole program and find the kernels or transfers that dominate. Fix those, not the rest.
Profile the dominant kernel and name its limit: memory bandwidth, compute throughput, or latency.
Make one change aimed at that limit.
Check the result is still correct, then time again. Keep the change only if the profile moved in the way you predicted.
The third step matters more than it looks. A change that speeds the kernel up for a reason you did not predict is a coincidence, and it will break the next time something shifts.
A minimal timing harness for step one looks like this:
cudaEvent_t t0, t1;
cudaEventCreate(&t0);
cudaEventCreate(&t1);
cudaEventRecord(t0);
for (int rep = 0; rep < 20; ++rep) myKernel<<<grid, block>>>(args);
cudaEventRecord(t1);
cudaEventSynchronize(t1);
float ms = 0.0f;
cudaEventElapsedTime(&ms, t0, t1);
printf("avg %.3f ms\n", ms / 20.0f);Run the loop several times and discard the first launch, because the first call pays context and module load costs. Timing a single cold launch is the most common source of wrong conclusions.
Classify the bottleneck: the roofline idea
A GPU has two ceilings. One is arithmetic throughput, the number of floating-point operations per second the multiprocessors can issue. The other is memory bandwidth, the bytes per second device memory can deliver. A kernel hits whichever it reaches first. The ratio that decides which is arithmetic intensity: floating-point operations performed per byte moved from memory.
Compute it from the code. The saxpy kernel y[i] = a * x[i] + y[i] does 2 operations per element, a multiply and an add, and moves 12 bytes: it reads x[i] and y[i] and writes y[i], four bytes each. Its intensity is 2 / 12, about 0.17 operations per byte. Every GPU can do far more arithmetic than it can feed from memory at that ratio, so saxpy is memory bound on every card, and nothing you do to the arithmetic can speed it up. The only improvements are moving fewer bytes or moving them more efficiently.
A tiled matrix multiply is the opposite case. In the tiled multiply post, each value loaded into shared memory is reused by every thread in the tile. For a tile width T, each loaded element serves T multiply-adds, so intensity grows with T, and a large enough tile makes the kernel compute bound.
The third category is latency bound. The kernel neither saturates memory nor arithmetic, because too few warps are in flight to hide the delay of each operation, or because dependent instructions wait on each other. Low occupancy, long dependency chains and frequent barriers cause it. Nsight Compute shows all three categories on its Speed of Light section, which the profiler reading post later in this cluster explains. For now, take the vocabulary: memory bound, compute bound, latency bound. Each has different fixes.
| Limit | Symptom in the profile | First fixes |
|---|---|---|
| Memory bound | DRAM throughput near peak, compute low | Fewer bytes, coalescing, reuse in shared memory, lower precision |
| Compute bound | Pipeline utilization near peak, memory low | Cheaper instructions, fast math, tensor cores, fewer ops |
| Latency bound | Both low, many stall cycles | Raise parallelism, more independent work per thread, fewer barriers |
Fix memory access first
Most kernels are memory bound, and memory access has the largest range between a bad pattern and a good one. Three ideas cover it: coalescing, reuse and avoiding the trip.
Coalescing
Threads in a warp issue their loads together. When the 32 addresses fall in a few contiguous 32-byte segments, the hardware services the whole warp with a few transactions. When they scatter, it takes many. A warp reading 32 consecutive floats touches 128 bytes, which is four 32-byte sectors, and uses every byte it fetches. A warp reading floats with a stride of 32 elements touches 32 different sectors and uses 4 bytes of each 32-byte sector, so the traffic is eight times what the useful data requires.
Compare two kernels that copy a matrix. The first lets neighboring threads read neighboring elements. The second gives each thread a whole row, so neighboring threads read addresses width elements apart:
__global__ void copyCoalesced(const float *in, float *out, int w, int h)
{
int x = blockIdx.x * blockDim.x + threadIdx.x; // fast index
int y = blockIdx.y * blockDim.y + threadIdx.y;
if (x < w && y < h) out[y * w + x] = in[y * w + x];
}
__global__ void copyStrided(const float *in, float *out, int w, int h)
{
int row = blockIdx.x * blockDim.x + threadIdx.x; // slow index on x
if (row < h)
for (int col = 0; col < w; ++col)
out[row * w + col] = in[row * w + col];
}The first kernel is the pattern to aim for. In the second, thread t and thread t + 1 read addresses w * 4 bytes apart. The post on uncoalesced access in this cluster goes through the diagnosis in the profiler. The rule you can apply by reading code is simple: the thread index that varies fastest, threadIdx.x, should multiply the smallest stride in the address.
Structure of arrays
Data layout decides whether the natural thread mapping is coalesced. An array of structs puts the fields of one element next to each other, so a kernel that reads only x from struct {float x, y, z;} skips two floats for every one it reads, using a third of each fetched sector. Splitting the fields into separate arrays makes the reads contiguous:
struct ParticlesAoS { float x, y, z; }; // x of consecutive threads is 12 bytes apart
struct ParticlesSoA { float *x, *y, *z; }; // x of consecutive threads is 4 bytes apartThe same reasoning applies to any field you read in isolation. If a kernel needs all three fields of an element together, a vector type such as float4 loaded as one 16-byte unit is also efficient, since one instruction fetches the aligned group.
Vector loads
Wider loads move more per instruction. Reading a float4 instead of four float values cuts the instruction count and keeps the address pattern coalesced, provided the pointer is 16-byte aligned. Memory from cudaMalloc is aligned to at least 256 bytes, so the base is fine, and an index you multiply by four stays aligned:
__global__ void scale4(const float4 *in, float4 *out, float k, int n4)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n4) {
float4 v = in[i];
v.x *= k; v.y *= k; v.z *= k; v.w *= k;
out[i] = v;
}
}Here n4 is the element count divided by four, so launch n4 threads, each handling four floats. Handle any leftover elements when the count is not a multiple of four with a scalar tail.
Reuse in shared memory
When many threads read the same global value, load it once into shared memory. Stencils, convolutions and matrix multiplies all follow the same plan: stage a tile with coalesced loads, synchronize and let the threads read their neighbors from the tile. The tiled multiply post is the worked case, and the bank conflict rules below keep the shared reads fast.
Bank conflicts
Shared memory is split into 32 banks, each four bytes wide, and a warp's accesses are served in one step only if no two threads address different words in the same bank. Two threads reading different words from one bank serialize. The usual cause is a column access into a two-dimensional tile whose row length is a multiple of 32: element (r, c) lives in bank (r * 32 + c) % 32, which is c for every row, so a column read hits one bank from all 32 threads. Padding each row by one float, declaring tile[32][33], shifts each row by one bank and removes the conflict. The bank conflict post in this cluster shows the measurement.
A complete example: matrix transpose in three steps
Transpose is the standard teaching case because it has no arithmetic. Everything is memory access, so you see the effect of each step directly. NVIDIA's CUDA samples use it for the same reason.
The naive version reads along rows, which coalesces, and writes along columns, which does not:
#define TILE 32
__global__ void transposeNaive(const float *in, float *out, int w, int h)
{
int x = blockIdx.x * TILE + threadIdx.x;
int y = blockIdx.y * TILE + threadIdx.y;
if (x < w && y < h)
out[x * h + y] = in[y * w + x]; // read coalesced, write stride h
}Consecutive threads share y and differ in x, so the read addresses are contiguous but the write addresses are h floats apart.
The second version stages a tile in shared memory so both the global read and the global write are coalesced. Threads write the tile in row order and read it in column order, which swaps the roles:
__global__ void transposeShared(const float *in, float *out, int w, int h)
{
__shared__ float tile[TILE][TILE];
int x = blockIdx.x * TILE + threadIdx.x;
int y = blockIdx.y * TILE + threadIdx.y;
if (x < w && y < h) tile[threadIdx.y][threadIdx.x] = in[y * w + x];
__syncthreads();
x = blockIdx.y * TILE + threadIdx.x; // swap block coordinates
y = blockIdx.x * TILE + threadIdx.y;
if (x < h && y < w) out[y * h + x] = tile[threadIdx.x][threadIdx.y];
}After the barrier, the output coordinates swap the block indices, so each warp writes 32 consecutive floats. The global traffic is now coalesced both ways. The price is the shared memory read tile[threadIdx.x][threadIdx.y], a column access, which suffers the 32-way bank conflict described above.
The third version pads the tile by one column:
#include <cstdio>
#include <cuda_runtime.h>
#define TILE 32
__global__ void transposePadded(const float *in, float *out, int w, int h)
{
__shared__ float tile[TILE][TILE + 1]; // +1 removes the bank conflict
int x = blockIdx.x * TILE + threadIdx.x;
int y = blockIdx.y * TILE + threadIdx.y;
if (x < w && y < h) tile[threadIdx.y][threadIdx.x] = in[y * w + x];
__syncthreads();
x = blockIdx.y * TILE + threadIdx.x;
y = blockIdx.x * TILE + threadIdx.y;
if (x < h && y < w) out[y * h + x] = tile[threadIdx.x][threadIdx.y];
}
int main()
{
const int w = 64, h = 32;
float hin[w * h], hout[w * h];
for (int i = 0; i < w * h; ++i) hin[i] = (float)i;
float *din, *dout;
cudaMalloc(&din, sizeof(hin));
cudaMalloc(&dout, sizeof(hout));
cudaMemcpy(din, hin, sizeof(hin), cudaMemcpyHostToDevice);
dim3 block(TILE, TILE);
dim3 grid((w + TILE - 1) / TILE, (h + TILE - 1) / TILE);
transposePadded<<<grid, block>>>(din, dout, w, h);
cudaMemcpy(hout, dout, sizeof(hout), cudaMemcpyDeviceToHost);
int bad = 0;
for (int y = 0; y < h; ++y)
for (int x = 0; x < w; ++x)
if (hout[x * h + y] != hin[y * w + x]) ++bad;
printf("out[1]=%.0f out[32]=%.0f mismatches=%d\n", hout[1], hout[32], bad);
cudaFree(din); cudaFree(dout);
return 0;
}out[1]=64 out[32]=1 mismatches=0The input is 32 rows of 64 values. After transposing, out has 64 rows of 32 values. out[1] is row 0, column 1 of the output, which is the input at row 1, column 0, value 64. out[32] is row 1, column 0 of the output, which is the input at row 0, column 1, value 1. A block of 32 by 32 is 1,024 threads, the maximum, so this tile size uses a full block; smaller tiles with more rows per thread are a common refinement. The host loop confirms every element.
What did each step buy? The naive kernel wastes global bandwidth on the strided write. The shared version fixes global traffic and adds a shared memory conflict. The padded version fixes both. You would confirm that with Nsight Compute by comparing the global store efficiency and the shared memory bank conflict counters across the three kernels, the way the profiler posts in this cluster describe.
Occupancy: enough warps, not the most warps
A multiprocessor hides latency by switching between warps. While one warp waits for a load, another runs. Occupancy is the ratio of resident warps to the maximum the multiprocessor supports, and it is limited by three resources: registers per thread, shared memory per block and the cap on threads and blocks. The earlier post on nvcc --resource-usage shows how to read the first two off the compiler's report and turn them into a block count.
Ask the runtime rather than doing the arithmetic by hand:
int blocksPerSm = 0;
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&blocksPerSm, myKernel, 256, 0);
cudaDeviceProp p;
cudaGetDeviceProperties(&p, 0);
float occupancy = (blocksPerSm * 256) / (float)p.maxThreadsPerMultiProcessor;
printf("blocks/SM=%d occupancy=%.2f\n", blocksPerSm, occupancy);Suppose it prints blocks/SM=6 occupancy=1.00 on a device with 1,536 resident threads per multiprocessor: six blocks of 256 threads fill it. If it prints blocks/SM=3 occupancy=0.50, you have half the warps available to hide latency.
Two facts keep occupancy in proportion. First, more occupancy helps only while latency is the limit. A kernel that already saturates memory bandwidth gains nothing from more warps. Second, you can trade occupancy for something else on purpose: giving each thread more registers lets it hold more independent values, which can beat a high occupancy. The post on when low occupancy is fine covers that trade, and the __launch_bounds__ post covers the compiler control. As a starting point, aim for the occupancy the calculator reports as sufficient to hide latency, usually somewhere between a third and full, and then let the profiler tell you whether the stall reasons point at latency.
Divergence: keep warps on one path
A warp executes one instruction at a time for all 32 threads. If threads of the same warp take different branches, the hardware runs each path in turn with the other threads masked off, so the branch costs the sum of both paths. This is warp divergence, and it matters only when the condition varies within a warp. A condition that is the same for the whole warp, such as blockIdx.x < 10, costs nothing.
Compare two ways to split work by parity:
// Diverges: neighboring threads alternate paths inside every warp.
if (threadIdx.x % 2 == 0) pathA(); else pathB();
// Does not diverge: whole warps share a path.
if ((threadIdx.x / 32) % 2 == 0) pathA(); else pathB();In the first, every warp runs both paths with half its lanes idle each time. In the second, each warp follows a single path. The refactor is possible only when the work assignment is flexible. Where it is not, such as a per-element test on data, you can reduce the cost by sorting or partitioning the data so similar elements sit together, or by replacing a branch with arithmetic that every thread executes, such as a select.
Short branches that only choose a value usually compile to predicated instructions with no divergence at all, and the compiler decides this. Look at the generated code with the technique in the PTX and SASS post later in this cluster before you rewrite a branch by hand.
Instruction-level work: ILP and cheaper math
When a kernel is compute bound or latency bound with enough occupancy, look at the instruction stream.
Instruction-level parallelism
A thread that issues independent instructions back to back keeps the pipeline full without needing other warps. A dependency chain, where each instruction needs the previous result, does not. Splitting an accumulation into several independent accumulators gives the hardware independent work:
// One accumulator: each add waits for the previous one.
float s = 0.0f;
for (int i = tid; i < n; i += stride) s += in[i];
// Four accumulators: four independent chains per thread.
float s0 = 0, s1 = 0, s2 = 0, s3 = 0;
int i = tid;
for (; i + 3 * stride < n; i += 4 * stride) {
s0 += in[i];
s1 += in[i + stride];
s2 += in[i + 2 * stride];
s3 += in[i + 3 * stride];
}
for (; i < n; i += stride) s0 += in[i]; // leftovers
float s = (s0 + s1) + (s2 + s3);Four loads are now in flight per thread, which also raises memory-level parallelism. The sum is computed in a different order, so the last bits can differ from the single-accumulator version, as in the reduction post.
Use the cheaper instruction when the accuracy allows it
CUDA offers fast intrinsics with reduced accuracy. __expf(x), __sinf(x) and __fdividef(x, y) map to fewer hardware instructions than expf, sinf and the division operator, and the programming guide lists their error bounds. The compiler flag -use_fast_math applies them across a file and also flushes denormals to zero, which is why it should be enabled only after you check the accuracy of your results. A narrower alternative is to call the intrinsic in the one hot expression where accuracy is not critical.
Integer division and modulo by a value that is not a compile-time constant are expensive, because the hardware has no single instruction for them. Use shifts and masks when the divisor is a power of two, and compute threadIdx.x & 31 rather than threadIdx.x % 32, though the compiler already does this when it sees the constant.
Lower precision and tensor cores
Moving half as many bytes is a direct win for memory-bound kernels, and half-precision arithmetic doubles throughput on hardware that supports it. The __half post in this cluster covers the types and the conversion rules. For dense matrix multiplication and convolution, tensor cores perform small matrix multiply-accumulate operations in hardware, which the WMMA post covers. Neither is free: both reduce precision, so validate with the accuracy test your application needs.
Launch overhead and small kernels
Each kernel launch costs a few microseconds of host and driver work, which is negligible next to a kernel that runs for milliseconds and dominant for a sequence of hundreds of tiny ones. The symptoms are a timeline with many small kernels separated by gaps. There are three remedies. Fuse neighboring kernels so intermediate results stay in registers instead of travelling through global memory, which also saves bandwidth. Batch many small problems into one launch with an extra grid dimension. And record a repeated sequence into a CUDA graph and launch it as one unit, the subject of the CUDA graphs post later in this cluster.
Fusion is the most valuable of the three, because it removes memory traffic as well as launch cost. Two elementwise kernels, one that scales and one that adds a bias, read and write the array twice. One fused kernel reads and writes it once:
__global__ void scaleThenBias(const float *in, float *out, float k, float b, int n)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = in[i] * k + b;
}For elementwise operations this halves the global traffic. Libraries such as Thrust achieve similar effects with fancy iterators, as the Thrust post shows.
Transfers: the other half of the runtime
The PCIe or NVLink link between host and device is far slower than device memory, so a kernel that is 10 times faster can still leave the program unchanged if transfers dominate. Three practices keep transfers from taking over.
First, move less. Keep data on the device across several kernels instead of copying results back after each, and reduce on the device before you copy, so you transfer a sum and not an array. Second, use pinned host memory, which lets the DMA engine work directly and makes asynchronous copies truly asynchronous, as the pinned memory post explains. Third, overlap: split the work into chunks and issue copies and kernels in several streams so the copy engines and multiprocessors run at the same time, the pattern the streams post builds.
Timeline tools show whether you did it right. If the copy rows and the kernel rows in Nsight Systems line up end to end with gaps between them, you are serial. Staggered rows mean the pipeline works.
Use the read-only path and constant memory deliberately
When a kernel only reads an array, tell the compiler. Marking pointers const __restrict__ states that the memory is not written through another pointer and does not alias, which lets the compiler route loads through the read-only data cache and reorder them:
__global__ void gather(const float *__restrict__ table,
const int *__restrict__ idx,
float *__restrict__ out, int n)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = table[idx[i]];
}The read-only cache post in this cluster explains __ldg and the cases where the compiler does it for you. Uniform values that every thread reads the same way, such as filter coefficients, belong in __constant__ memory, where a warp reading one address is served by one broadcast.
Registers, spills and local memory
If the compiler runs out of registers it spills values to local memory, which lives in device memory. Each spill is an extra store and later load. The report from nvcc --resource-usage shows spill bytes, and any nonzero number in a hot kernel deserves attention. Fixes include shortening the live ranges of variables, unrolling less, moving data to shared memory and, as a last resort, relaxing a __launch_bounds__ hint that forced a tight register budget. The opposite mistake also happens: capping registers hard to raise occupancy, and ending with spills that cost more than the occupancy gained.
A related and subtler form is a dynamically indexed per-thread array. The compiler can keep a small array in registers only if every index is known at compile time, which fully unrolled loops provide. A dynamic index forces the array into local memory. Where possible, restructure so the index is a loop counter of an unrolled loop, or use shared memory.
Atomics and contention
Atomic operations to one address serialize. A histogram or a counter updated by every thread turns a parallel kernel into a queue. Privatize the updates in shared memory or registers and merge once per block, and aggregate within a warp before touching global memory, as the atomics post shows. Where a reduction can replace the atomic, prefer the reduction: it is deterministic for a fixed configuration and scales better.
Tooling: which tool answers which question
Use the right instrument for each question, in this order.
| Question | Tool | Post in this cluster |
|---|---|---|
| Where does the whole program spend time? | Nsight Systems | Timeline profiling |
| Why is this one kernel slow? | Nsight Compute | Single-kernel analysis and the Speed of Light chart |
| Which regions are which? | NVTX ranges | Annotating code |
| Is the code even correct? | compute-sanitizer | Memory error checks |
| What did the compiler produce? | nvcc --resource-usage, cuobjdump, PTX and SASS | Registers and SASS reading |
Correctness comes first. Run the sanitizer before you optimize, because a racy kernel that produces the right answer by luck will be wrong the moment you change the timing, and every speed number you took from it is meaningless. Optimization changes the order in which threads run, which exposes bugs that were always there.
A worked decision: which fix for which profile
Concrete profiles make the table above usable. Take three kernels and the single most likely first action for each.
Kernel A reads a 2D array column by column. Profile: DRAM throughput is low, and the global load efficiency line shows a small percentage of requested bytes being used. That is uncoalesced access. Swap the roles of the thread indices or stage through a padded shared tile, as in the transpose.
Kernel B runs a long chain of dependent floating-point operations per element and reads each element once. Profile: low DRAM throughput, low pipeline utilization, high occupancy, with stalls on execution dependencies. That is latency from dependency chains. Split the chain into independent accumulators or process two elements per thread.
Kernel C is a reduction launched on a small array of 4,096 elements. Profile: the kernel takes a few microseconds and the timeline shows more time in launch gaps than in execution. No kernel change helps. Batch the launches, fuse it into the producer kernel or capture the sequence in a graph.
The point of the exercise is that the three kernels are all slow and share no fix.
When not to optimize
Optimization has costs: code that is harder to read, tuned to one architecture and fragile under change. Skip it where the kernel is not on the critical path, where the program is dominated by transfers you cannot avoid, or where a library already provides a tuned implementation. For matrix multiplies, FFTs, sorts and reductions, call cuBLAS, cuFFT, Thrust or CUB, as the earlier posts in this cluster show. Write your own kernel when the operation is not in a library, when you can fuse it with neighboring work to save a pass over memory, or when the library's interface forces a copy you can avoid. Stop when the profile shows the kernel near the bandwidth or compute peak for its class, since there is nothing left to win.
Portability is a boundary too. A kernel tuned for one GPU generation may regress on another because register files, shared memory sizes and cache behavior differ. Keep the unoptimized version, record why each change was made and re-measure on each architecture you ship for. Consider parameterizing tile sizes and unroll factors with templates, so you can retune per architecture without rewriting the kernel.
A checklist to run on any slow kernel
Is the answer correct under
compute-sanitizer, includingracecheckfor shared memory?Is this kernel or transfer actually what dominates the program, per a timeline?
Is the kernel memory bound, compute bound or latency bound, per Nsight Compute?
For memory bound: is every global access coalesced, and is every value reused that can be?
For shared memory: are there bank conflicts, and is padding or a swizzle needed?
For latency bound: is occupancy limited by registers or shared memory, and is there enough independent work per thread?
For compute bound: can lower precision, an intrinsic or a tensor core do the same job?
Are there spills, a stack frame or dynamic local arrays in the compiler report?
Are many small kernels or transfers better fused, batched or captured in a graph?
After the change, does the profile show the metric you targeted improving?
A second worked example: a one-dimensional stencil
The transpose had no arithmetic. A stencil mixes a little arithmetic with heavy reuse, so it shows how shared memory reuse is decided. Each output is the average of an element and its two neighbors: out[i] = (in[i-1] + in[i] + in[i+1]) / 3. The naive kernel is one line:
__global__ void blur3Naive(const float *in, float *out, int n)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i > 0 && i < n - 1)
out[i] = (in[i - 1] + in[i] + in[i + 1]) * (1.0f / 3.0f);
}Each thread reads three global values, and each interior value is read by three different threads, so the kernel requests three times the data it needs. Hardware caches rescue most of that: neighboring threads read overlapping addresses, the first read brings a sector into the cache and the other two hit. That is why a naive stencil often performs better than the access count suggests, and it is also why you must profile before adding shared memory. If the profile shows the L1 hit rate is already high and DRAM traffic is close to one read and one write per element, the naive kernel is near the bandwidth limit and shared memory has nothing left to save.
When the stencil is wider, say radius 8, or two-dimensional, the cache stops covering it, and a shared tile with a halo pays off:
#include <cstdio>
#include <cuda_runtime.h>
#define BLOCK 256
#define RADIUS 1
__global__ void blur3Shared(const float *in, float *out, int n)
{
__shared__ float tile[BLOCK + 2 * RADIUS];
int g = blockIdx.x * blockDim.x + threadIdx.x; // global index
int l = threadIdx.x + RADIUS; // index in the tile
tile[l] = (g < n) ? in[g] : 0.0f;
if (threadIdx.x < RADIUS) { // left halo
int gl = g - RADIUS;
tile[l - RADIUS] = (gl >= 0) ? in[gl] : 0.0f;
}
if (threadIdx.x >= blockDim.x - RADIUS) { // right halo
int gr = g + RADIUS;
tile[l + RADIUS] = (gr < n) ? in[gr] : 0.0f;
}
__syncthreads();
if (g > 0 && g < n - 1)
out[g] = (tile[l - 1] + tile[l] + tile[l + 1]) * (1.0f / 3.0f);
}
int main()
{
const int n = 1024;
float h[n], r[n];
for (int i = 0; i < n; ++i) h[i] = (float)(i % 3); // 0 1 2 0 1 2 ...
float *dIn, *dOut;
cudaMalloc(&dIn, sizeof(h));
cudaMalloc(&dOut, sizeof(h));
cudaMemcpy(dIn, h, sizeof(h), cudaMemcpyHostToDevice);
cudaMemset(dOut, 0, sizeof(h));
blur3Shared<<<(n + BLOCK - 1) / BLOCK, BLOCK>>>(dIn, dOut, n);
cudaMemcpy(r, dOut, sizeof(r), cudaMemcpyDeviceToHost);
printf("out[1]=%.1f out[2]=%.1f out[255]=%.1f out[256]=%.1f\n",
r[1], r[2], r[255], r[256]);
cudaFree(dIn); cudaFree(dOut);
return 0;
}out[1]=1.0 out[2]=1.0 out[255]=1.0 out[256]=1.0Any three consecutive values of the repeating pattern 0, 1, 2 sum to 3, so every interior output is 1.0. The two indices that sit on a block boundary, 255 and 256, are the ones that exercise the halo loads, and they come out right. A bug in the halo code would show up there first, which is why you test boundary indices. The threads at the block edges do extra work to load the halo, and that is the price of the technique: for a block of 256 threads and radius 1, two extra loads per 256, which is a small overhead.
The memory hierarchy in one picture
It helps to hold the whole path in your head. A load from a thread goes through the registers, the L1 cache and shared memory of its multiprocessor, then the L2 cache shared by the whole GPU, then device memory. Each level has a different capacity and bandwidth, and the programming guide and best practices guide describe the sizes per architecture. Three consequences follow from the structure.
First, the unit of transfer between device memory and the caches is a small segment, 32 bytes in current architectures, and every request fetches whole segments. The efficiency of an access pattern is the useful bytes divided by the fetched bytes, which is why a warp reading 32 consecutive floats is perfect and a warp reading one float from each of 32 rows is eight times wasteful.
Second, L2 is a shared resource across all multiprocessors, so one block's data can serve another block's loads if they touch the same lines close in time. This is why two-dimensional kernels often schedule neighboring blocks to neighboring data, and why a grid-stride loop that walks through memory in a streaming pattern gets good L2 behavior.
Third, writes are handled differently from reads. A partial write to a segment may force the memory system to merge it with existing data. Writing complete, aligned segments, as the padded transpose does, avoids that.
Reading stall reasons
Nsight Compute reports, for each warp scheduler, why warps did not issue an instruction in a given cycle. The names to know are few. A long scoreboard stall means the warp is waiting for a global or local memory load. A short scoreboard stall means it waits for shared memory or a special function unit. A barrier stall means it waits at __syncthreads(). A math pipe throttle stall means the arithmetic pipeline is full. A not selected stall means the warp was ready but another warp was chosen, which is a good sign. The stall name points to the fix: long scoreboard stalls dominate memory-bound kernels and call for better access patterns or more independent loads, barrier stalls suggest unbalanced work between barriers, and math throttle means the kernel is compute bound.
Warp State Statistics (illustrative values)
Stall Long Scoreboard 62%
Stall Short Scoreboard 4%
Stall Barrier 3%
Stall Not Selected 9%A profile like the one above says to spend your time on global memory access. The percentages here are an illustration of how to read the section, and your kernel will show its own.
Asynchronous copies and newer hardware features
Recent architectures add hardware that moves data from global to shared memory without passing through registers. The cuda::memcpy_async function and the pipeline interface let a thread issue the copy for the next tile while it computes on the current one, which hides global memory latency inside a single block, and the Hopper generation adds a tensor memory accelerator and thread block clusters with distributed shared memory. Those are expert tools with their own posts in this cluster. The ordering of this guide holds even for them: they are the last step, after access patterns, occupancy and instruction mix are in order, because they add real complexity and pay off only for kernels already tuned.
Anti-patterns that show up in reviews
| Pattern | Why it hurts | Better |
|---|---|---|
cudaDeviceSynchronize() after every launch in production | Removes all overlap and serializes the host | Synchronize once, or use events and streams |
cudaMalloc and cudaFree inside a loop | Both can synchronize the device and are slow | Allocate once, or use a stream-ordered pool |
| One thread per block, many blocks | A warp runs with one active lane | Use at least a warp of threads |
Reading struct fields one at a time from an array of structs | Wastes most of each sector | Structure of arrays |
| Atomics on a single global counter in the hot loop | Serializes on one address | Privatize and merge, or reduce |
| Block size chosen by habit | May starve the multiprocessor or waste registers | Query occupancy and measure |
| Tuning on a tiny input | Launch cost dominates the timing | Use sizes that match production |
Comparing floating-point results with == | Reordering changes the last bits | Compare with a tolerance |
Guarding performance in CI
A tuned kernel regresses silently when someone changes the surrounding code. Two cheap guards help. Keep a benchmark that times each hot kernel on a fixed input with events, and fail the build if the time exceeds a stored baseline by a generous margin, since run-to-run noise on shared machines is real. And store the output of nvcc --resource-usage for the hot kernels, failing the build if registers jump or spills appear, which signals a compiler or code change that probably cost occupancy. Neither check proves the code is fast, and both catch the common accidents.
Putting numbers on a change without a stopwatch
Not every claim needs a benchmark. Some changes are provable from the code, and writing the proof down is faster and more reliable than a noisy timing. Count bytes. For the padded transpose, each element is read once and written once, so the traffic is 2 * 4 bytes per element, which is the minimum any transpose can move. If a profile later shows the kernel's DRAM throughput close to the card's peak bandwidth, the kernel is at its limit and you stop. If it shows half, you know there is a factor of two to find, and you know where to look: the stores, the loads or the launch.
Count instructions the same way. A loop that executes four loads and four adds per element with the loop counter test amortized over four elements has an instruction overhead of roughly one test per four elements, and unrolling by eight halves it. That is a claim about the instruction stream, checkable in the SASS, and it is only worth making for kernels that are compute bound, since a memory-bound kernel spends its time waiting regardless.
Count warps. A block of 128 threads on a multiprocessor limited to 1,536 resident threads can hold 12 blocks, or 48 warps, if registers and shared memory allow, and fewer if they do not. Writing those numbers into a comment next to the launch gives the next reader the reasoning behind the block size, and tells them what to recheck when the architecture changes.


