Passing large matrices to RcppArmadillo function without creating copy (advanced constructors)

帅比萌擦擦* 提交于 2019-11-28 20:54:22

This has been discussed extensively in the Rcpp mailing list. See this thread. The solution that has been implemented in RcppArmadillo is to pass the arma::mat by reference. Internally this will call the advanced constructor for you.

So with this version, you would do something like this:

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::vec test(const arma::mat& M) {
    // do whatever with M
    ...
}

And the data from the R matrix is not copied but rather borrowed. More details in the thread.

Here are some benchmarks comparing the time it takes to copy or pass by reference:

                 expr      min        lq    median        uq      max neval
    arma_test_value(m) 3540.369 3554.4105 3572.3305 3592.5795 4168.671   100
      arma_test_ref(m)    4.046    4.3205    4.7770   15.5855   16.671   100
arma_test_const_ref(m)    3.994    4.3660    5.5125   15.7355   34.874   100

With these functions:

#include <RcppArmadillo.h>
using namespace Rcpp ;

// [[Rcpp::depends("RcppArmadillo")]]

// [[Rcpp::export]]
void arma_test_value( arma::mat x){}

// [[Rcpp::export]]
void arma_test_ref( arma::mat& x){}

// [[Rcpp::export]]
void arma_test_const_ref( const arma::mat& x){}

With the CRAN version of RcppArmadillo, you would use that sort of syntax:

void foo( NumericMatrix x_ ){
    arma::mat M( x_.begin(), x_.nrow(), x_.ncol(), false ) ;
    // do whatever with M
}

This has been used in many places, including several articles in the Rcpp gallery.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!