我们正在尝试优化我们的C++代码,以下是使用Eigen库进行矩阵计算的代码:
#include<Eigen/Dense>
int main(){
MatrixXd P = MatrixXd::Random(30,30); // a random double 30 x 30 matrix P
MatrixXd M = MatrixXd::Random(30,30); // a random double 30 x 30 matrix M
Matrix<double, 30, 30> I;
I.setIdentity(); // I is an 30 x 30 identity matirx
P = (I-M)*P
return 0;
}
其中它们都是n x n矩阵,I是单位矩阵。 我们发现重写上述矩阵计算
P= (I- M)*P
作为
P = P-M*P
在使用gcc 6.2编译器的Linux Ubuntu系统中,可以实现4-8倍的速度提升。我意识到编译器可能不知道什么是单位矩阵和I * P = P这个事实,但我仍然无法理解是什么原因导致了效率的如此大幅提高。有人知道可能导致如此显著改进的原因吗?
dgemm
http://www.netlib.org/lapack/lapack-3.1.1/html/dgemm.f.html ,而第一个版本无法通过单个函数匹配,因此需要使用临时变量进行计算(首先计算I - M
,然后乘以P
并替换旧值)。 - alfC