There is a package Parallel
detectCores()
: return how many cores exist on your PC.
cl <- makeCluster(np)
: initialize a cluster mc with np processes.
Apply Operations using Clusters:
clusterCall
, clusterEvalQ
, clusterApply
, clusterExport
, clusterMap
,
parLapply
, parSapply
, parApply
, parRapply
, parCapply
stopCluster(cl)
: release the occupied cores.
An example
Check how many cores exist on my PC.
library(parallel)
detectCores()
## [1] 12
Define a function.
sim <- function(x){
rnorm(1, mean = x)
}
Use parallel
to speed up the calculation.
SimParallel <- function(x, nc){
cl <- makeCluster(nc)
result = parSapply(cl = cl, x, sim)
stopCluster(cl)
return(result)
}
out <- SimParallel(1:10000, 8)