C ++ performance, compiler optimization, empty function in .cpp

I have a very simple class, name it Basic, which is used in almost all other files in a larger project. In some cases, debugging output is required, but in release mode this should not be enabled and should be NOOP.

Currently, there is a definition in the header that turns the macro on or off, depending on the setting. So it is definitely NOOP when turned off. I am wondering if I have the following code, if the compiler (MSVS / gcc) can optimize a function call, so that it again is NOOP. (By doing this, the switch can be in .cpp, and switching will be much faster, compilation / connection time).

--Header--
void printDebug(const Basic* p);

class Basic {
   Basic() {
      simpleSetupCode;

      // this should be a NOOP in release, 
      // but constructor could be inlined
      printDebug(this);
   }
};
--Source--
// PRINT_DEBUG defined somewhere else or here
#if PRINT_DEBUG
void printDebug(const Basic* p) {
   // Lengthy debug print
}
#else
void printDebug(const Basic* p) {}
#endif
+5
5

, - , .

+2

, , printDebug . printDebug , , , . - , . PRINT_DEBUG, , TRACE:

#define PRINT_DEBUG    // optional
#ifdef PRINT_DEBUG
#define PRINT_DEBUG_CALL(p) printDebug(p)
#else
#define PRINT_DEBUG_CALL(p)
#endif


void printDebug(const Basic* p);

class Basic {
   Basic() {
      simpleSetupCode;

      // this should be a NOOP in release, 
      // but constructor could be inlined
      PRINT_DEBUG_CALL(this);
   }
};
--Source--
// PRINT_DEBUG defined somewhere else or here
#if PRINT_DEBUG
void printDebug(const Basic* p) {
   // Lengthy debug print
}
#endif
+1
#if PRINT_DEBUG
#define printDebug _real_print_debug
#else
#define printDebug(...)
#endif

, .

+1

errm, -?

, - :

  #define DEBUG_TRACE(p)
  #ifdef PRINT_DEBUG
    printDebug(p);
  #else
    ;
  #endif
0

. LLVM . . .

Expecting such an optimization, you can do the following. Define a macro that allows you to include the following statement, depending on whether DEBUG is defined or not.

#ifdef DEBUG
#define IF_DEBUG (false) {} else
#else
#define IF_DEBUG 
#endif

You can use it like this:

   Basic() {
      simpleSetupCode;

      // this should be a NOOP in release, 
      // but constructor could be inlined
      IF_DEBUG printDebug(this);
   }

which is already much more readable than

   Basic() {
      simpleSetupCode;

      // this should be a NOOP in release, 
      // but constructor could be inlined
#if DEBUG
      printDebug(this);
#endif
   }

Please note that you can use it as if it were a keyword

IF_DEBUG {
   printDebug(this);
   printDebug(thas);
}
0
source

All Articles