This forum has been archived. All content is frozen. Please use KDE Discuss instead.

How to make this code faster

Tags: None
(comma "," separated)
Blu
Registered Member
Posts
2
Karma
0

How to make this code faster

Wed Aug 15, 2012 1:16 am
Hello,

I am using C Mex file with Matlab and Eigen3 library. Currently my code is doing at least 6-7 times slower than someone else's code written in CLAPACK. Unfortunately, I don't have access to that other code (at least for now).

Since I am new to Eigen, I hope that I would get some hints as how to get this code more efficient. Sine my whole code is long and confusing to see, I am posting a portion of it here:

Code: Select all
   MatrixXd AmEigen = Map<MatrixXd, 0, OuterStride<>>(mxGetPr(ssGetSFcnParam(S, AMINDEX)), length, length, OuterStride<>(length));
   VectorXd bEigen = Map<VectorXd> (mxGetPr(ssGetSFcnParam(S, BINDEX)),length);
   VectorXd xEigen = Map<VectorXd> ((real_T *) ssGetInputPortSignal(S,1),length);
   /*Similar mapping for other variables*/
   xTildaEigen = xHatEigen - xEigen;
   
   Map<VectorXd>(dstateVector,length) = AmEigen*xHatEigen + bEigen*(((real_T) *u[0]) + thetaEigen.dot(xEigen));
   
   Map<VectorXd>(&dstateVector[(int)stateAccess[THETAINDEX-1]],length) = (*gammaTheta) * proj(thetaEigen, -xTildaEigen.dot(PbEigen)*xEigen, *thetaBound, *epsilonTheta, LEigen, oThetaEigen);

   Map<VectorXd>(&dstateVector[(int)stateAccess[XFINDEX-1]],lengthFilter) = AfEigen*xfEigen + bfEigen*kfEigen*(((real_T) *r[0])*kgEigen - (thetaEigen.transpose()*xEigen));

(All functions starting with 'ss' are provided by Matlab and are used in my code here just to get access to varaibles)

I don't have a good reason in my head by I suspect Map template to be slowing the process down. Does that make sense?

Can anyone give me any tips to make it efficient?
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: How to make this code faster

Mon Aug 27, 2012 1:28 pm
You can avoid mem alloc and copies by naming the Map objects:

MatrixXd AmEigen = Map<MatrixXd, 0, OuterStride<>>(mxGetPr(ssGetSFcnParam(S, AMINDEX)), length, length, OuterStride<>(length));

=>

Map<MatrixXd, 0, OuterStride<> > AmEigen(mxGetPr(ssGetSFcnParam(S, AMINDEX)), length, length, OuterStride<>(length));


You can avoid a temporary by isolating a matrix*vector product:

Map<VectorXd>(dstateVector,length) = AmEigen*xHatEigen + bEigen*(((real_T) *u[0]) + thetaEigen.dot(xEigen));

=>

Map<VectorXd>(dstateVector,length) = bEigen*(((real_T) *u[0]) + thetaEigen.dot(xEigen));
Map<VectorXd>(dstateVector,length).noalias() += AmEigen*xHatEigen + bEigen*(((real_T) *u[0]) + thetaEigen.dot(xEigen));


Same for the last line.


Finally, make sure you compile your c++ code with optimization enabled, otherwise Eigen is very slow.


Bookmarks



Who is online

Registered users: Baidu [Spider], Bing [Bot], Google [Bot], Yahoo [Bot]