Sign in to follow this  
akira32

if and #ifdef in shader code for performance

Recommended Posts

if and #ifdef which is better used in shader code and does not affect the performance seriously?
#ifdef _DEBUG_
    return float4(1.0f,0,0,1);
#else
    clip(-1);
#endif

if (bDeug)
    return float4(1.0f,0,0,1);
else
    clip(-1);

Share this post


Link to post
Share on other sites
There is a huge difference.

#ifdef is a preprocessor keyword (as it starts with #). It is executed BEFORE the shader is COMPILED and can be used to exclude some parts of the source code.

if() is branch statement. It is executed at runtime of the shader and can have quite severe performance penalities.

Always use #ifdef if already you know what you want to be executed at the time the shader is compiled.

Best regards,
Porthos

Share this post


Link to post
Share on other sites
well the whole point of #ifdef's are to either have the code contained within it compiled and run/accessable or not compiled with the rest of the program at all. If you don't want to be able to toggle the code contained on an off then use #ifdef and just define debug or whatever when you want to compile a test version, and then undefine it and recompile for a normal version... but if you want to be able to toggle the section running while the program is currently running then of course you have to use a normal variable.

in terms of performance - one little if statement isn't going to make a bit of difference if the test fails and the code doesnt run.

maybe a better solution is


#ifdef _DEBUG_
if (Debug) return float blah blah
else clip(-1);
#else
clip(-1);
#endif



this way you can compile your program with the option of toggling a debug var on and off, or you can compile the whole idea right out and just have it clip(-1).

Share this post


Link to post
Share on other sites
'if' has several meanings. It may be calculated at compile time if it refers to a uniform parameter. The uniform parameter's value is supplied when the shader is compiled ("compile ps_2_0 shader(parameter);").

For a program-wide debug flag, preprocessor may be good. If you want to select debug for specific shaders, at runtime, you can have different techniques for them, and compile with different uniform debug parameters.

(For normal code, 'if' can still be either defined as 'branch' or 'flatten', which will produce different code.)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this