# NOT RUN {
library(HelpersMG)
x <- 1:1000
funx <- function(y) {
mint <- rep(NA, length(y))
for (i in seq_along(y)) {
k <- rnorm(runif(n = 1, 50, 50), mean=10, sd=2)
mint[i] <- mean(k)
}
mint
}
# Note that parallel computing is not always the best solution !
(tp <- system.time({
m <- lapply(X=x, FUN=funx)
}))
(tp <- system.time({
m <- universalmclapply(X=x, FUN=funx, forking=FALSE)
}))
(tp <- system.time({
m <- universalmclapply(X=x, FUN=funx, forking=TRUE)
}))
### An example using clusterExport
# Here no error is generated because environment was exported
# However forking is not possible in windows and non parallel code is ran
pp <- runif(100)
x <- 1:100
funx1 <- function(y) {pp[y]*10}
u <- universalmclapply(x, FUN=funx1, forking=TRUE)
# Here an error is generated because environment was not exported when parLapplyLB is used
pp <- runif(100)
x <- 1:100
u <- universalmclapply(x, FUN=funx1, forking=FALSE)
# here no error is generated because the variable pp is exported
pp <- runif(100)
x <- 1:100
u <- universalmclapply(x, FUN=funx1, forking=FALSE,
clusterExport=list(varlist=c("pp"), envir=environment()))
### An example using clusterEvalQ
asc("a") # asc() is a function from packages HelpersMG
funx2 <- function(y) {asc("a")*10}
# In unix, the loaded packages are visible from all cores
x <- 1:100
u <- universalmclapply(x, FUN=funx2, forking=TRUE)
# In windows, the loaded packages are not visible from all cores
x <- 1:100
u <- universalmclapply(x, FUN=funx2, forking=FALSE)
# In windows, the loaded packages are not visible from all cores
x <- 1:100
u <- universalmclapply(x, FUN=funx2, forking=FALSE,
clusterEvalQ=list(expr=expression(library(HelpersMG)))
)
### If package pbapply is available, progress bar can be shown
m <- universalmclapply(X=x, FUN=funx, forking=FALSE, progressbar=TRUE)
m <- universalmclapply(X=x, FUN=funx, forking=TRUE, progressbar=TRUE)
# }
Run the code above in your browser using DataLab