Inline function v. Macro in C — What's the Overhead (Memory/Speed)?

后端 未结 9 1137
太阳男子
太阳男子 2020-12-02 13:18

I searched Stack Overflow for the pros/cons of function-like macros v. inline functions.

I found the following discussion: Pros and Cons of Different macro function

相关标签:
9条回答
  • 2020-12-02 14:00

    as others have said, it mostly depends on the compiler.

    I bet "pow" costs you more than any inlining or macro will save you :)

    I think its cleaner if its an inline function rather than a macro.

    caching and pipelining are really where you are gonna get good gains if you are running this on a modern processor. ie. remove branching statements like 'if' make enormous differences ( can be done by a number of tricks )

    0 讨论(0)
  • 2020-12-02 14:06

    Calling an inline function may or may not generate a function call, which typically incurs a very small amount of overhead. The exact situations under which an inline function actually gets inlined vary depending on the compiler; most make a good-faith effort to inline small functions (at least when optimization is enabled), but there is no requirement that they do so (C99, §6.7.4):

    Making a function an inline function suggests that calls to the function be as fast as possible. The extent to which such suggestions are effective is implementation-defined.

    A macro is less likely to incur such overhead (though again, there is little to prevent a compiler from somehow doing something; the standard doesn't define what machine code programs must expand to, only the observable behavior of a compiled program).

    Use whatever is cleaner. Profile. If it matters, do something different.

    Also, what fizzer said; calls to pow (and division) are both typically more expensive than function-call overhead. Minimizing those is a good start:

    double ratio = SigmaSquared/RadialDistanceSquared;
    double AttractiveTerm = ratio*ratio*ratio;
    EnergyContribution += 4 * Epsilon * AttractiveTerm * (AttractiveTerm - 1.0);
    

    Is EnergyContribution made up only of terms that look like this? If so, pull the 4 * Epsilon out, and save two multiplies per iteration:

    double ratio = SigmaSquared/RadialDistanceSquared;
    double AttractiveTerm = ratio*ratio*ratio;
    EnergyContribution += AttractiveTerm * (AttractiveTerm - 1.0);
    // later, once you've done all of those terms...
    EnergyContribution *= 4 * Epsilon;
    
    0 讨论(0)
  • 2020-12-02 14:07

    Please review the CERT Secure coding standard talking about macros and inline functions in terms of security and bug arousing , i do not encourage using function-like macros , because : - Less Profiling - Less Traceable - Harder to debug - Could Lead to severe Bugs

    0 讨论(0)
提交回复
热议问题