Contents
When is a branch in a shader is free?
If the condition is uniform (i.e. constant for the entire pass), then the branch is essentially free because the framework will essentially compile two versions of the shader (branch taken and not) and choose one of these for the entire pass based on your input variable.
Why does branch divergence slow down the shader?
Branch divergence in warp makes all parts of the branch execute in sequence which slows down the shader. Branching divergence between warps does not affect runtime. Branch execution on gpus is surprisingly deep, and there are many edge cases I didn’t address and I also didn’t touch gpu vendors other than Nvidia.
How many branches should a shader have per warp?
Here’s another shader which should have roughly four branches per warp. This shader will take at least 4n cycles. However, let’s look a second shader: This shader should run roughly twice as fast as the other shader even though roughly the same number of pixels take each branch.
How does branch divergence in independent thread scheduling work?
Independent Thread Scheduling gets around these locking problems by interlacing the two diverging paths. Branch divergence in warp makes all parts of the branch execute in sequence which slows down the shader. Branching divergence between warps does not affect runtime.
When to use if statement in shader stack?
In this case, definitely go for the if statement as it will make your shader faster. If the condition varies per vertex/pixel, then it can indeed degrade performance and older shader models don’t even support dynamic branching.
Which is the best shader stack to use?
The newest, most general CUDA/compute-shader friendly nVidias might have the best implementation; older cards might have a poorer implementation. The worse case is you may find many threads executing both sides of if/else statements. One of the great tricks with shaders is learning how to leverage this massively parallel paradigm.
Do You mark if statements as branch or flatten?
Also note that you can explicitly mark if statements in DirectX shaders as [branch] or [flatten]. The flatten style gives you the right result, but always executes all in the instructions. If you don’t explicitly choose one, the compiler can choose one for you — and may pick [flatten], which is no good for your example.
What’s the best way to use a shader?
One of the great tricks with shaders is learning how to leverage this massively parallel paradigm. Sometimes that means using extra passes, temporary offscreen buffers and stencil buffers to push logic up out of the shaders and onto the CPU.
Is it possible to use dynamic branching in Unity?
On older mobile devices which only support OpenGL ES 2.0, they always “flatten” as they do not support dynamic branching at all. This was true for early desktop hardware as well, which is why there’s a stigma against using if conditions in shaders.