gpt4 book ai didi

c++ - Visual Studio 2010 - 函数未内联 - 为什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:43:03 27 4
gpt4 key购买 nike

我有一个计算内积的通用函数:

template < typename _A >
inline typename _A::value_type innerProduct( const _A& A,
const typename _A::index_type& row0,
const typename _A::index_type& row1,
const typename _A::index_type& col,
const typename _A::size_type& n )
{
typedef typename _A::value_type value_type;
typedef typename _A::index_type index_type;

value_type sum = value_type( );

for( index_type i = 0; i < n; ++i )
{
sum += A( row0, i ) * A( row1, i );
}

return sum;
}

在计算 cholesky 分解时,我多次调用该函数。因为函数调用的开销很大(~11%!),所以应该避免。在我的简单世界中,我认为该函数非常小,编译器会将其内联。我多次检查了编译器选项,但我认为它们很好。我用例如/Ox/O2/Ob2/GL。我还检查了函数在调用函数之前是否对编译器可见。但是函数永远不会内联。唯一可行的选择是使用关键字 __forceinline 显式定义函数。

那么我必须告诉编译器什么样的选项来内联函数?函数内联与否,编译器的判断标准是什么?

最佳答案

Microsoft 未记录在 inline 关键字时函数可能未内联的具体原因。 (我能找到的最接近的是 compiler warning C4710 的文档。)inline 关键字只是一个提示,编译器使用试探法来确定内联是否值得优化。在很多情况下,内联会损害性能,例如,如果它增加寄存器压力。

您已经找到了这个问题的解决方案:使用 __forceinline 关键字告诉编译器您知道得更多。要使其在调用站点有条件,请创建两个版本的 innerProduct 函数,一个带有 __forceinline ,一个没有。看起来你可以通过调用前者来实现后者。像这样的东西:

__forceinline value_type innerProduct_forceinline(...) {
...
return sum;
}

inline value_type innerProduct(...) {
return innerProduct_forceinline(...);
}

关于c++ - Visual Studio 2010 - 函数未内联 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25711893/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com