Elementwise matrix multiplication: R versus Rcpp (How to speed this code up?)

后端 未结 3 1175
北荒
北荒 2021-02-03 14:30

I am new to C++ programming (using Rcpp for seamless integration into R), and I would appreciate some advice on how to speed up some calcu

3条回答
  •  Happy的楠姐
    2021-02-03 15:22

    If you want to speed up your calculations you will have to be a little careful about not making copies. This usually means sacrificing readability. Here is a version which makes no copies and modifies matrix X inplace.

    // [[Rcpp::export]]
    NumericMatrix Rcpp_matvecprod_elwise(NumericMatrix & X, NumericVector & y){
      unsigned int ncol = X.ncol();
      unsigned int nrow = X.nrow();
      int counter = 0;
      for (unsigned int j=0; j

    Here is what I get on my machine

     > library(microbenchmark)
     > microbenchmark(R=R_matvecprod_elwise(X, e), Arma=A_matvecprod_elwise(X, e),  Rcpp=Rcpp_matvecprod_elwise(X, e))
    
    Unit: milliseconds
     expr       min        lq    median       uq      max neval
        R  8.262845  9.386214 10.542599 11.53498 12.77650   100
     Arma 18.852685 19.872929 22.782958 26.35522 83.93213   100
     Rcpp  6.391219  6.640780  6.940111  7.32773  7.72021   100
    
    > all.equal(R_matvecprod_elwise(X, e), Rcpp_matvecprod_elwise(X, e))
    [1] TRUE
    

提交回复
热议问题