R fast cbind matrix using Rcpp

和自甴很熟 提交于 2019-12-04 02:47:34
tonytonov

Borrowing an idea from this comment by Romain Francois on one of my previous Rcpp adventures,

func1 <- 'NumericMatrix mmult1(NumericMatrix a, NumericMatrix b) {
  int acoln = a.ncol();
  int bcoln = b.ncol();
  NumericMatrix out = no_init_matrix(a.nrow(), acoln + bcoln);
  for (int j = 0; j < acoln + bcoln; j++) {
    if (j < acoln) {
      out(_, j) = a(_, j);
    } else {
      out(_, j) = b(_, j - acoln);
    }
  }
  return out;
}'

cppFunction(func1)
set.seed(42)
a <- matrix(rnorm(1e7), 1e3)
b <- matrix(runif(1e7), 1e3)

identical(mmult(a, b), mmult1(a, b))
#TRUE

library(microbenchmark)
microbenchmark(mmult(a, b), 
               mmult1(a, b), 
               cbind(a, b),
               times = 10)

#Unit: milliseconds
#         expr    min     lq   mean median    uq   max neval
#  mmult(a, b)  69.64  70.52  89.71  72.28 128.8 136.6    10
# mmult1(a, b)  50.84  50.95  69.65  51.43 111.6 114.4    10
#  cbind(a, b) 192.35 194.67 201.13 195.30 196.1 255.9    10

Not a huge deal, but not bad either for such a trivial change.

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