I'm a beginner in C++ and I would appreciate advices to optimize the following function I wrote with Eigen (in fact, to be used with RcppEigen).
So far, I observe a 3.5x speed-up compared to the corresponding function written in R, and I was wondering whether I could gain more.
Note that I'm working with very large matrices, so I rely on maps to avoid copies from the corresponding objects in R.
Thanks in advance for your help!
#include <RcppEigen.h>
using namespace Rcpp;
using namespace Eigen;
typedef Map<ArrayXd> MapArr1D;
typedef Map<ArrayXXd> MapArr2D;
typedef Map<MatrixXd> MapMat;
typedef Map<VectorXd> MapVec;
// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::export]]
void myFct(const MapMat M1, const MapMat M2, MapMat M3, MapMat M4, MapArr2D A1,
MapArr2D A2, const MapArr1D a1, const MapArr1D a2, const MapArr1D a3,
const MapArr1D a4, const MapArr1D a5, const double d1) {
for (int j = 0; j < M1.cols(); ++j) {
M4.noalias() -= M1.col(j) * M3.row(j);
A1.row(j) = a1 * a2 * ((M2 - M4).transpose() * M1.col(j)).array();
A2.row(j) = exp(-Fct(a3(j) - a4(j) - a5 / 2 - d1 / 2 -
pow(A1.row(j).transpose(), 2) / (2 * a1) - log(a1) / 2));
M3.row(j) = A1.row(j) * A2.row(j);
M4.noalias() += M1.col(j) * M3.row(j);
}
}
where Fct
is some other function.
myFct
is calculating. MathJax is available, if you need to write mathematical text. \$\endgroup\$ – 200_success Mar 14 '17 at 8:41myFct(x)
computeslog(1 + exp(x))
using the "log-sum-exp" trick to avoid overflow. \$\endgroup\$ – user79097 Mar 14 '17 at 8:50