Thread: Use inline functions instead of macros?

  1. #1
    Registered User
    Join Date
    Mar 2010
    Location
    China
    Posts
    74

    Cool Use inline functions instead of macros?

    The code is here. C Mozilla Pastebin - collaborative debugging tool

    I'm writing heap sort as an inline function and a macro with the same implementation. In my test, the inline function runs much slower than the macro (the macro costs 1.0 sec and the function costs 5.0 sec, with gcc -O3).
    Is the inline funcion always sucking like this?

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    A quick note to start: you should not use two leading underscores on identifiers. Such identifiers are in the implementation's namespace, and you're not supposed to use them. A single leading underscore is sometimes in the implementation's namespace, so I'd recommend avoiding that, too. Trailing underscores are fine, and should serve the same purpose without clashing with the compiler.

    Now, I notice you do not use “inline” at all, so I'm not sure why you're expecting any inlining. At any rate, the problem is probably an inlining issue, but perhaps not in the way you're expecting.

    Gcc can optimize memcpy() by using its own builtin copy if it thinks that'd be a good idea. With your macro code, gcc can easily see that __size holds a constant value; since this value is sizeof(int), it can generate extremely efficient code for the copy (the equivalent of assigning an int to an int). The function code, on the other hand, has to assume that size can be any value from 0 to SIZE_MAX. A very intelligent compiler could probably try inlining hsort_fcall() and see that the size is constant, allowing it to generate the same code (it looks like Intel's compiler does this); but gcc does not appear to be able to do this, so it has to actually call memcpy() in libc.

    The macro can also inline intcpy() if the compiler so desires, but the function cannot, similar to how it can't know the size: it always has to go through the function pointer, meaning it always has to call a function.

    These, I suspect, are the primary reasons your macro is faster.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. parameterized macros vs. functions
    By Tbrez in forum C Programming
    Replies: 3
    Last Post: 04-02-2009, 12:33 PM
  2. Macros vs Inline Functions
    By vb.bajpai in forum C Programming
    Replies: 4
    Last Post: 08-02-2007, 11:51 AM
  3. Macros as functions
    By Darklighter in forum Windows Programming
    Replies: 4
    Last Post: 11-25-2006, 08:56 AM
  4. Macros Vs Inline functions
    By passionate_guy in forum C++ Programming
    Replies: 4
    Last Post: 04-29-2006, 02:52 AM
  5. Inline Assembler Macros?
    By Aidman in forum C++ Programming
    Replies: 14
    Last Post: 07-15-2003, 05:10 AM