R语言并行运算示例 parallel 包
library(parallel)
#example 1
cl <- makeCluster(getOption("cl.cores", 2))
clusterApply(cl, c(9,5), get("+"),1) #加
parSapply(cl, c(9,5), get("+"), 3)
stopCluster(cl)
#example 2
xx <- 1
cl <- makeCluster(getOption("cl.cores", 2))
clusterExport(cl, "xx")
cy = function(y) xx + y
clusterCall(cl, cy,2)
stopCluster(cl)
xx <- 1;y=2
cl <- makeCluster(getOption("cl.cores", 2))
clusterExport(cl, c("xx",'y'))
cy = function() xx + y
clusterCall(cl, cy)
stopCluster(cl)
#example 3
no_cores = 3
cl = makeCluster(no_cores)
df = function(exponent) 2^exponent
parLapply(cl, 2:4, df)
stopCluster(cl)
#example 4
no_cores = detectCores() - 1
cl<-makeCluster(no_cores)
base <- 2
clusterExport(cl, "base")
ef = function(exponent) base^exponent
parLapply(cl, 2:4,ef)
stopCluster(cl)
#example 5
no_cores = detectCores() - 1
cl<-makeCluster(no_cores)
base <- 2
clusterExport(cl, "base")
parSapply(cl, 2:4, function(exponent) base^exponent)
stopCluster(cl)
#example 6
ncore = 3
cl = makeCluster(ncore)
myf = function(x) x^3
mr = clusterApplyLB(cl, x=1:ncore, fun=myf)
mr
stopCluster(cl)