c++ - 内联函数是否作为参数传递,真正在 C/C++ 中内联执行?

标签 c++ c hpc

我有一个很长(迭代次数)的 for 循环,我希望可以对其某些部分进行个性化设置。代码如下所示:

function expensive_loop( void (*do_true)(int),  void (*do_false)(int)){
    for(i=0; i<VeryLargeN; i++){
       element=elements[i]
       // long computation that produce a boolean condition
       if (condition){ 
         do_true(element); 
       }else{
         do_false(element);
       }
    }
}

现在,问题是每次调用 do_truedo_false 时,由于堆栈的 push/pop 会产生开销,从而破坏了高性能代码。

为了解决这个问题,我可以简单地创建多个 expensive_loop 函数的拷贝,每个拷贝都有自己的 do_true 和 do_false 实现。这将使代码无法维护。

那么,如何制作迭代的内部部分,使其可以个性化,同时仍然保持高性能?

最佳答案

请注意,该函数接受指向函数的指针,因此可以通过指针调用这些函数。如果 expensive_loop 和那些函数的定义可用并且没有违反编译器内联限制,优化器可能会通过函数指针内联这些调用。

另一种选择是使该算法成为接受可调用对象(函数指针、具有调用运算符的对象、lambda)的函数模板,就像标准算法一样。这样编译器可能会有更多的优化机会。例如:

template<class DoTrue, class DoFalse>
void expensive_loop(DoTrue do_true, DoFalse do_false) { 
    // Original function body here.
}

-Winline g++ 的编译器开关:

-Winline

Warn if a function can not be inlined and it was declared as inline. Even with this option, the compiler will not warn about failures to inline functions declared in system headers.

The compiler uses a variety of heuristics to determine whether or not to inline a function. For example, the compiler takes into account the size of the function being inlined and the the amount of inlining that has already been done in the current function. Therefore, seemingly insignificant changes in the source program can cause the warnings produced by -Winline to appear or disappear.

当通过指针调用函数时,它可能不会警告函数未被内联。

关于c++ - 内联函数是否作为参数传递,真正在 C/C++ 中内联执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40872841/

相关文章:

C++ : Check if the template type is one of the variadic template types

c - 使用 C 进行客户端服务器编程速度慢

C - 为什么 printf() 中的输出如此奇怪

python - 使用 celery 处理巨大的文本文件

c++ - std::bind 导致析构函数出现段错误

c++ - 如何在 C++ 中指向函数

c++ - 在 C++ 中运行 CMD 行使用变量(不是字符串文字)作为参数

c - 直接将数字分配给 char 和一点算术

c++ - 使用 OpenMP 优化双线性插值

amazon-ec2 - Ray 未在 EC2 上启动 worker