开发者

How to determine C++ inline functions?

I have the following piece of code.

#开发者_开发百科include <iostream>

using namespace std;

inline void inlinefunc() { cout << "hello" << endl; }
void func() { cout << "hello" << endl; }

bool isInlineFunc(void (*f)()) { return (f == inlinefunc); }

void print(void (*f)()) {
    cout << (isInlineFunc(f)?"inline - ":"normal -");
    f();
}

int main() {
    void (*f)();

    f = inlinefunc;
    print(f);

    f = func;
    print(f);
}

How do I generically write isInlineFunc?


What do you mean generically? Do you want to have a function that tells you if another function is declared inline? That can't be done.

Also note that by taking the address of an inline function, the implementation is forced to actually have an out of line implementation of the function.


You don't.
The compiler is basically allowed to do whatever it wants with regards to inlining functions. A function can be inlined in one place and not inlined in another place.

If you're thinking about this, you're probably prematurely optimizing something.


You can't. According to the C++ standard [basic.def.odr] (D refers to the definition in question):

... If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined.

Taking the address of a function, inline or otherwise, must result in the same behavior as if there were a single definition of that function. For inline functions, it means the address is the same.


In general, compiler can apply any optimization it chooses, as long as it doesn't change the semantics of your code.

Inlining is just an optimization strategy. "Detecting" whether the function was inlined or not would mean that the semantics depends on the optimization, in direct violation of the above.


You really can't - even with GCC, function's declared with __attribute__((always_inline)) won't be inlined if they don't meet the compiler's criteria for things that would increase the speed of the program.

Inlining functions can have serious negative effects on performance, and the compiler is almost always the only thing in the right position to know if that's the case. Inlining functions thwarts CPU architectural features like code cache and branch predictors, and even lower-level features like instruction decode cache (and bandwidth).

In short, there are some things that any modern CPU will do at tremendous speed, and C/C++ function calls are right up there. Profiling function call overhead is almost certainly going to give within-error measurements of your profiling overhead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜