__attribute__((always_inline))
是否可以强制gcc内联函数?
应该需要。我非常推崇手动内联。当然,过度使用会造成问题。但通常情况下,在优化代码时,会发现有一两个函数必须内联,否则性能会急剧下降。而且,据我的经验,当使用内联关键字时,C编译器通常不会自动将这些函数内联。
我完全愿意让编译器为我大部分的代码进行内联。只有在那半打或者更少的绝对至关重要的情况下,我才非常在意。人们认为“编译器在这方面做得很好。”请拿出证据来证明。到目前为止,我从未见过一个C编译器在没有使用某种强制内联语法(msvc上的__forceinline
,gcc上的__attribute__((always_inline))
)的情况下自动内联我告诉它的至关重要的代码片段。
inline
关键字:__attribute__((always_inline)) inline YourFunc(...
否则会出现警告信息:warning: always_inline function might not be inlinable [-Wattributes]
。 - slashmais是的,它会生效。这并不意味着这是一个好主意。
根据GCC优化选项文档,你可以使用参数调整内联。
-finline-limit=n
By default, GCC limits the size of functions that can be inlined. This flag
allows coarse control of this limit. n is the size of functions that can be
inlined in number of pseudo instructions.
Inlining is actually controlled by a number of parameters, which may be specified
individually by using --param name=value. The -finline-limit=n option sets some
of these parameters as follows:
max-inline-insns-single is set to n/2.
max-inline-insns-auto is set to n/2.
我建议更详细地阅读有关内联的所有参数,并适当设置它们。
__forceinline
(对于MSVC)和__attribute__((always_inline))
(对于所有其他编译器)。在各种紧密循环中,从基本乘法到正弦等操作,性能均有25-35%的显著提升。.text
部分,以便实现“模糊链接”(请参见https://gcc.gnu.org/onlinedocs/gcc-4.8.0/gcc/Vague-Linkage.html)。通过强制内联,您基本上失去了在不同编译单元中显式特化模板函数的能力。 - Géza Török你也可以使用__always_inline
。我一直在使用这个函数来编写GCC 4.8.1的C++成员函数。但是在GCC文档中没有找到一个好的解释。
inline
和__attribute__((always_inline))
。我刚在带有GCC的Android NDK r10d上测试了一下。也许不是标准环境,但从我所读到的来看,这个要求对所有平台都是相同的。 - rwong