R语言并行运算示例 parallel 包

本文通过多个实例展示了如何使用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)


转载于:https://www.cnblogs.com/arcserver/p/9882522.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值