编译器是否优化了通过指针调用平凡函数? [英] Do compilers optimize away calls to trivial functions made through pointers?

查看:394
本文介绍了编译器是否优化了通过指针调用平凡函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个函数接受一个函数指针:

Say I have a function that takes a function pointer:

int funct(double (*f)(double));

我传递的函数实际上不做任何事情:

And I pass it a function that doesn't actually do anything:

double g(double a) { return 1.0;}
//...
funct(g);

编译器是否会优化调用 g ?还是会有开销吗?如果它有开销,多少?

Will the compiler optimize out the calls to g? Or will this still have overhead? If it does have overhead, how much? Enough that it is worth overloading the function to receive both function pointers and constant values?

推荐答案

新版本的GCC(4.4及更高版本) )可以使用选项 -findirect-inlining 来内联和优化已知的函数指针。这只有当GCC也知道所有使用指针的代码时才有效。

Newer versions of GCC (4.4 and later) can inline and optimize a known function pointer using the option -findirect-inlining. This only works when GCC also knows all of the code that uses the pointer.

例如,C库函数 qsort 不会从此优化中受益。 qsort的编译机器代码在库中,它需要一个函数指针,编译器不能改变它。

For example, the C library function qsort will not benefit from this optimization. The compiled machine code for qsort is in the library, it expects a function pointer and the compiler cannot change that.

但是,如果你有自己的qsort实现将其放置在头文件中,或者您使用了非常新的GCC链接时优化功能,那么GCC 能够接受您的调用代码,指向的函数,以及您的qsort源代码并编译它

However, if you had your own implementation of qsort and you placed it in a header file or you used the very new GCC link-time optimization features, then GCC would be able to take your calling code, the function pointed to, and your qsort source and compile it all together, optimized for your data types and your comparison function.

现在,只有当函数调用开销比函数本身大得多时,这才是真正重要的。在你没有什么功能的例子中,使用函数指针是严重的开销。在我的qsort比较的例子中,函数指针调用也是相当昂贵的。但在其他一些应用程序,如Windows事件分派,几乎不重要。

Now, the only times that this really matters is when the function call overhead is much larger than the function itself. In your example of a function that does nothing much, using a function pointer is serious overhead. In my example of a qsort comparison, the function pointer call is also quite expensive. But in some other application like Windows event dispatch, it hardly matters.

由于你使用C ++,你应该学习模板。模板函数可以接受所谓的函数对象,它只是实现 operator() 它可以接受函数指针。传递一个函数对象将允许C ++编译器内联和优化几乎所有的代码。

Since you are using C++ you should study templates. A template function can accept a so-called function object which is just an object that implements operator() and it can accept function pointers. Passing a function object will allow the C++ compiler to inline and optimize almost all of the code involved.

这篇关于编译器是否优化了通过指针调用平凡函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆