When is “inline” ineffective? (in C)

前端 未结 12 659
鱼传尺愫
鱼传尺愫 2020-12-09 10:56

Some people love using inline keyword in C, and put big functions in headers. When do you consider this to be ineffective? I consider it s

12条回答
  •  忘掉有多难
    2020-12-09 11:31

    An example to illustrate the benefits of inline. sinCos.h :

    int16 sinLUT[ TWO_PI ]; 
    
    static inline int16_t cos_LUT( int16_t x ) {
        return sin_LUT( x + PI_OVER_TWO )
    }
    
    static inline int16_t sin_LUT( int16_t x ) {
        return sinLUT[(uint16_t)x];
    }
    

    When doing some heavy number crunching and you want to avoid wasting cycles on computing sin/cos you replace sin/cos with a LUT.

    When you compile without inline the compiler will not optimize the loop and the output .asm will show something along the lines of :

    ;*----------------------------------------------------------------------------*
    ;*   SOFTWARE PIPELINE INFORMATION
    ;*      Disqualified loop: Loop contains a call
    ;*----------------------------------------------------------------------------*
    

    When you compile with inline the compiler has knowledge about what happens in the loop and will optimize because it knows exactly what is happening.

    The output .asm will have an optimized "pipelined" loop ( i.e. it will try to fully utilize all the processor's ALUs and try to keep the processor's pipeline full without NOPS).


    In this specific case, I was able to increase my performance by about 2X or 4X which got me within what I needed for my real time deadline.


    p.s. I was working on a fixed point processor... and any floating point operations like sin/cos killed my performance.

提交回复
热议问题