Instantly share code, notes, and snippets.

Embed
What would you like to do?
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