gpt4 book ai didi

c++ - 重复相同计算的优化

转载 作者:太空宇宙 更新时间:2023-11-04 13:48:02 25 4
gpt4 key购买 nike

考虑以下两个函数:

std::pair<double,Vector> myMatrixOperation1(Matrix const& A, Vector const& V) {
Vector AV = A*V;
double norm_A_V = std::sqrt(dot(V,AV));

return make_pair(norm_A_V,AV);
}

std::pair<double,Vector> myMatrixOperation2(Matrix const& A, Vector const& V) {
return make_pair( norm(V,A) , A*V );
}
double norm(Vector const& V, Matrix const& innerProductMatrix) {
double norm_A_V = std::sqrt(dot(V,innerProductMatrix*V));
}

他们显然做同样的事情,除了矩阵- vector 乘积保证在第一个函数中只计算一次。

但是,第二个函数更具可读性,因为它经过重构以完全分离关注点:关于任意内积的 vector 范数的概念被抽象到一个单独的函数中。

现在的问题是,在没有任何优化的情况下,矩阵 vector 乘积现在被计算了两次。

我的问题如下:编译器是否足够聪明,只计算一次矩阵 vector 乘积?如果是,我需要做什么?

我想至少我需要内联 norm() 函数。另外,关于 operator*(Matrix const& A, Vector const& V),懒惰求值有什么帮助吗? (旁注:我正在使用 Eigen 库)

注意:我知道一个类似的问题:Will the compiler optimize repeated math computations? .但是,请注意我的问题对编译器来说更难,因为 operator*(Matrix const& A, Vector const& V) 不是内置的,因此编译器应该需要一些保证

编辑:

在进一步思考维基百科的引文 ( http://en.wikipedia.org/wiki/Optimizing_compiler ) 之后:

For example, in some languages functions are not permitted to have side effects. Therefore, if a program makes several calls to the same function with the same arguments, the compiler can immediately infer that the function's result need be computed only once. In languages where functions are allowed to have side effects, another strategy is possible. The optimizer can determine which function has no side effects, and restrict such optimizations to side effect free functions. This optimization is only possible when the optimizer has access to the called function.

编译器似乎可以用第一个函数替换第二个函数,前提是 operator+ 是纯函数(即:无副作用)。根据https://stackoverflow.com/a/5464114/1583122 , 在 C++ 中,可以通过告诉编译器一个函数是 constexpr,只有 constexpr 函数调用,并且有 const 参数来保证编译器的纯度。所以我认为编译器有可能保证这样的优化,只要满足一些要求。此外,请注意,在 C++14 中,对 constexpr 函数的限制已大大减少

最佳答案

如果速度优化在此代码中很重要,我根本不会依赖编译器行为。

即使聪明的编译器发现了这个技巧(我对此表示怀疑,因为这会涉及相当多的语义洞察力——使函数内联可能会提示编译器),您也无法保证另一个编译器会看到它。甚至是相同的 future 版本!

经常出现这样的数值算法依赖于中间结果的重用。如果您清楚地评论说您保留结果以备后用,我认为没有可读性问题。代码紧凑并不总是意味着代码可读性。

关于c++ - 重复相同计算的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24892071/

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