C ++ matrix computation efficiency

We are trying to optimize our C ++ code, and we have the following mathematical calculation (using the Eigen library)

#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;

   }

Where are they all nxn-matrices, and I am the identity matrix. We found a rewrite of the above matrix calculation

   P= (I- M)*P

a

   P = P-M*P

results in ~ 4-8x acceleration on a Linux ubuntu system using the gcc 6.2 compiler. I understand the fact that the compiler may not know anything about the identity matrix and the fact I * P = P, but still can not plunge into the head, which increases efficiency. Does anyone know the possible reasons that make such significant improvements?

+6
source share
1 answer

, I.identity(); . I.setIdentity(), P = (MatrixXd::Identity(30,30)-M)*P. , Eigen, , 30x30 I M ( ). , ( , ).

I.Identity(), , ​​ -, . I, I, , , NaN denormal, . , , .

, , :

P -= M*P;

MatrixXd Pnew = P - M*P;
+1

Source: https://habr.com/ru/post/1016738/


All Articles