2021年4月2日星期五

Avoid too many "declare same elements of Rcpp List" in nested loops

I would like to ask about how to save computational time about accessing List in nested loop. Here is an Rcpp example including two functions:

#include <RcppArmadillo.h>  // [[Rcpp::depends(RcppArmadillo)]]  #include <Rcpp.h>    // [[Rcpp::export]]  void first(const Rcpp::List ETA            ,const int N            ,const int I                        ) {         for(int i = 0; i < I; ++i) {          arma::rowvec eta = ETA[i];          for(int n = 0; n < N; ++n) {              // use eta to do some calculation          }      }  }    // [[Rcpp::export]]  void second(const Rcpp::List ETA             ,const int N             ,const int I                        ) {         for(int n = 0; n < N; ++n) {          for(int i = 0; i < I; ++i) {              arma::rowvec eta = ETA[i];              // use eta to do some calculation          }      }  }  

Compare the time in R:

Rcpp::sourceCpp("test.cpp") # save the above code as "test.cpp"  ETA = list()  for (i in 1:10) ETA[[i]] = rep(0,i)  N = 10^7  I = 10  ptm <- proc.time(); first(ETA,N,I); print((proc.time() - ptm))  #    user  system elapsed   #       0       0       0   ptm <- proc.time(); second(ETA,N,I); print((proc.time() - ptm))  #    user  system elapsed   #    1.65    0.00    1.65  

Here the ETA is a list whose each element can either have dynamic length (vector) or dynamic dimension (matrix). In this code, the first way is much faster than the second way. But for practical needs, the second way can reduce computational time when there are other variables iterated over n.

Questions:

For either first way or second way, can we declare the eta outside the loops so that we don't need to declare the same eta so many times?

https://stackoverflow.com/questions/66902176/avoid-too-many-declare-same-elements-of-rcpp-list-in-nested-loops April 01, 2021 at 05:43PM

没有评论:

发表评论