Last active
July 23, 2018 06:38
-
-
Save YulongNiu/9331ea0d3ef46f0571c5f2dc061c3f8a to your computer and use it in GitHub Desktop.
Test Rcpp parallel with R versions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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