6

For debugging I have many calls to a debug log function in my application. Of course in the production version these debugging calls need to be skipped. Instead of writing:

#if DEVEL == 1
    Log::debug(...);
#endif

around all calls to the debug function I decided the write the following in the debug function itself:

#if DEVEL != 1
    return;
#endif

Will the overhead of the useless function call be avoided by the compiler or am I better off by using (many ugly) #if #endif construction for performance reasons?

3 Answers 3

7

Instead of worrying about optimizer, you can do a simple trick:

#if DEVEL == 1
#define LOG_DEBUG(...) Log::Debug(__VA_ARGS__)  // variadic macro
#else
#define LOG_DEBUG
#endif

Now use LOG_DEBUG everywhere to keep it simple.

Sign up to request clarification or add additional context in comments.

4 Comments

Nice. Why doesn't the #else version take parameters, though?
@Kerrek, because there are only 2 conditions. If it's not DEVEL == 1 then it will be surely DEVEL != 1.
No sorry, what I meant is why does the first version of LOG_DEBUG have arguments (parentheses), but the second doesn't? If you write LOG_DEBUG("hello"), then the second macro would expand to "hello", not nothing, wouldn't it?
No, in the second case LOG_DEBUG will be replaced by nothing, regardless of arguments.
5

If the function is available for inlining (e.g. it is implemented in the header) then the optimizer will have no trouble getting rid of the function call and thus leave you with no overhead.

2 Comments

Even if it's not defined in the header file the call will most likely be removed by link-time optimizations.
Better to be removed at compile time, so the call doesn't impact register allocation or prolog/epilog for a leaf versus non-leaf caller function
2

Why don't you check?

With gcc just compile with -S, and look at the output.

1 Comment

and turn on the optimizer: -O or -O3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.