[Rcpp-devel] copying or not when convering to arma

Dirk Eddelbuettel edd at debian.org
Thu Jul 11 09:50:39 CEST 2013


On 10 July 2013 at 11:58, Gabor Grothendieck wrote:
| Suppose we have this program where we have started and ended with SEXP
| and written out the as and wrap conversions to make them explicit.
| 
| How many times is the data copied?
| Does as copy the underlying data?
| Does wrap?
| Is it copied elsewhere?
| Which file in the source code would one look to determine this?
| If it does copy the data is there some way to tell as and wrap to just
| point to it to avoid copying?
| 
| #include <RcppArmadillo.h>
| // [[Rcpp::depends(RcppArmadillo)]]
| // [[Rcpp::export]]
| SEXP test(SEXP v) {
|    arma::vec va = Rcpp::as<arma::vec>(v);
|    SEXP vs = Rcpp::wrap(va);
|    return vs;
| }

You can reduce this to 

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::vec gabortest(arma::vec v) {
   return v;
}

because as<> and wrap() can get called automagically given that
RcppArmadillo provides them.

You want to start with the few header files we add to Armadillo in
RcppArmadillo (ie above the armadillo_bits/ directory which is verbatim
Armadillo.

In this case, a copy is made. How to avoid this has been discussed a dozen
times here and is shown in FastLm.cpp as well.  

As for counts of objects:  I'd rather trust a good memory profiler than my
word :)  But approximately, one each as we have to go from R/Rcpp to
Armadillo (as use the easy way; for alternatives see above).  If you use just
Rcpp no copies are being made. 

Cheers from Sydney,  Dirk
 
| # run it from R
| sourceCpp("test.cpp")
| test(c(1.2, 1.3, 1.4))
| 
| 
| --
| Statistics & Software Consulting
| GKX Group, GKX Associates Inc.
| tel: 1-877-GKX-GROUP
| email: ggrothendieck at gmail.com
| _______________________________________________
| Rcpp-devel mailing list
| Rcpp-devel at lists.r-forge.r-project.org
| https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com


More information about the Rcpp-devel mailing list