A warp-uniform branch sends every thread in a warp down the same path, avoiding branch divergence within that warp. One way to do this is to branch on blockIdx: threads in a block share its block index, and a warp never spans multiple blocks. section 14.3
Choose a path by block
For example, test whether blockIdx.x is even to choose between two workloads. Every thread in that block makes the same choice. By contrast, testing threadIdx.x < 16 splits a warp’s threads across two paths. section 14.3
Use this strategy when the work can be divided at block level:
- Branch on blockIdx rather than threadIdx so each warp follows one path. section 14.4
- For short, cheap branches without memory side effects, predication may be preferable; for randomly intermixed data, consider sorting if its cost is worthwhile. section 14.4
// blockIdx.x is the same for all threads in a warp: no divergence
if (blockIdx.x % 2 == 0)
heavyWork1(); #A
else
heavyWork2(); #BThe blockIdx condition is shared by threads in a block, so each warp takes the same branch. section 14.3
