Skip to content

Instantly share code, notes, and snippets.

@YulongNiu
Last active July 23, 2018 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YulongNiu/9331ea0d3ef46f0571c5f2dc061c3f8a to your computer and use it in GitHub Desktop.
Save YulongNiu/9331ea0d3ef46f0571c5f2dc061c3f8a to your computer and use it in GitHub Desktop.
Test Rcpp parallel with R versions
library('microbenchmark')
library('Rcpp')
library('RcppParallel')
library('foreach')
library('parallel')
library('doParallel')
library('iterators')
sourceCpp('testrcpp.cpp')
##~~~~~~~~~~~~~~~~~~~R parallel~~~~~~~~~~~~~~~~~
SqrtRforeach <- function(orig, n = 8) {
registerDoParallel(cores = n)
itx <- iter(orig)
res <- foreach(i = itx, .combine = c) %dopar% {
return(sqrt(i))
}
## stop multiple cores
stopImplicitCluster()
return(res)
}
SqrtRParSapply <- function(orig, n = 8) {
cl <- makeCluster(n)
registerDoParallel(cl)
res <- parSapply(cl,
orig,
sqrt)
## stop multiple cores
stopImplicitCluster()
return(res)
}
SqrtR <- function(orig) {
res <- numeric(length(orig))
for (i in orig) {
res[i] <- sqrt(orig[i])
}
return(res)
}
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
##~~~~~~~~~~~~~~~~test~~~~~~~~~~~~~~~~~~~~~
tmp1 <- runif(1e+7)
all.equal(SqrtCpp(tmp1),
sqrt(tmp1),
SqrtCppPara(tmp1),
SqrtCppArma(tmp1))
microbenchmark(
SqrtCpp(tmp1),
sqrt(tmp1),
SqrtCppPara(tmp1),
SqrtCppArma(tmp1))
all.equal(SqrtCpp(tmp1),
sqrt(tmp1),
SqrtR(tmp1),
SqrtRforeach(tmp1),
SqrtRParSapply(tmp1),
SqrtCppPara(tmp1),
SqrtCppArma(tmp1))
microbenchmark(
SqrtCpp(tmp1),
sqrt(tmp1),
SqrtR(tmp1),
SqrtRforeach(tmp1),
SqrtRParSapply(tmp1),
SqrtCppPara(tmp1),
SqrtCppArma(tmp1))
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment