优化代码中是否调用了空函数?

发布于 2024-11-18 04:51:08 字数 298 浏览 1 评论 0原文

如果没有定义TEST宏,我想知道这两段代码是否有性能差异:

void Func1(int a) {
   // ...
}

#ifdef TEST
Func1(123);
#endif

并且:

void Func2(int a) {
#ifdef TEST
    // ...
#endif
}

Func2(123);

如果没有定义TESTFunc2将变成编译器根本不应该调用的空函数,不是吗?

If the TEST macro is not defined, I would like to know whether there is a performance difference in these two pieces of code:

void Func1(int a) {
   // ...
}

#ifdef TEST
Func1(123);
#endif

and:

void Func2(int a) {
#ifdef TEST
    // ...
#endif
}

Func2(123);

With TEST not defined, Func2 would become an empty function that the compiler should not call at all, isn't it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独守阴晴ぅ圆缺 2024-11-25 04:51:08

这很大程度上取决于对 Func2 的特定调用是否内联。如果是,那么优化编译器应该能够对空函数进行内联调用,就像根本不调用它一样。如果它不是内联的,那么它会被调用并立即返回。

只要函数定义在包含对 Func2 的调用的 TU 中可用,就没有明显的理由不内联它。

这一切都依赖于 123 是一个文字这一事实,因此评估调用的参数没有副作用。即使函数调用没有效果,也必须对 args 进行求值,因此:

int i = 0;

/* 'i' is incremented, even if the call is optimized out */
Func2(++i);

/* 'i' is not incremented when 'TEST' is undefined */
#ifdef TEST
Func1(++i);
#endif

It pretty much comes down to whether that particular call to Func2 is inlined or not. If it is, then an optimizing compiler ought to be able to make an inlined call to an empty function the same as not calling it at all. If it isn't inlined, then it's called and returns immediately.

As long as the function definition is available in the TU containing the call to Func2, there's no obvious reason it won't be inlined.

This all relies on the fact that 123 is a literal, so evaluating the arguments of your call has no side-effects. The args have to be evaluated even if the function call has no effect, so:

int i = 0;

/* 'i' is incremented, even if the call is optimized out */
Func2(++i);

/* 'i' is not incremented when 'TEST' is undefined */
#ifdef TEST
Func1(++i);
#endif
瑾兮 2024-11-25 04:51:08

优化通常是特定于编译器的。 AFAIK,语言标准没有对什么应该被优化、什么不应该被优化做出任何声明。 (尽管我承认我还没有阅读语言规范本身。)

每个编译器都有自己的一组选项,通过这些选项来启用/禁用特定的优化步骤。

所以答案是明确的“这取决于”,并且“你必须检查自己才能确定”。

(但是,如果一个半途而废的优化器会让这样的构造未得到优化,我会感到非常惊讶。)

Optimizations are generally compiler-specific. The language standard does not, AFAIK, make any statements about what should and what should not be optimized away. (Although I admit I haven't read the language specification itself.)

Each compiler has its own set of options by which to enable / disable specific optimization steps.

So the answer is a definite "it depends", and "you would have to check yourself to be sure".

(However, I'd be quite surprised if a halfway decent optimizer would leave such a construct unoptimized.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文