[Rcpp-devel] arma::mat and Rcpp::NumericMatrix

c s conradsand.arma at gmail.com
Tue Sep 20 07:28:14 CEST 2011

Jeffrey Pollock Fri Sep 16 15:48:03 CEST 2011 wrote:
> I've recently started looking into the speed gains from using Rcpp and
> have began looking into the arma library too. Ive written a small loop
> to fill in a matrix and done so using the arma::mat class and the
> Rcpp::NumericMatrix class. In this case, the Rcpp::NumericMatrix
> class was slightly faster. Is this usually the case, or have I written
> quite inefficient code in some parts?

Armadillo by default checks the indices to matrices, submatrices,
vectors, etc to ensure they are within bounds.  This does have some
overhead, ranging from 10% to 20%.

The reason for the default behaviour is to ensure rapid development:
catch all the bugs in your algorithm first, then optimise.

The bounds checks can be explicitly turned off by defining
ARMA_NO_DEBUG before including any Armadillo header
eg. #define ARMA_NO_DEBUG

Alternatively, instead of using the () operator for matrices, eg. X(1,2),
you can use the .at() accessor, eg. X.at(1,2).

In both cases, turning off bounds checks is only recommended if your
code has been debugged, or you have explicitly checked the bounds
ARMA_NO_DEBUG also turns off many other run-time checks, so use it
only if you know what you're doing.

Lastly, if you're interfacing with R via Rcpp, for maximum speed it's
useful to avoid copying data:

More information about the Rcpp-devel mailing list