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)



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM