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)


posted @   junjunang  阅读(2831)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示