我正在使用for循环计算置换测试统计信息。我希望使用并行处理来加速这一点(特别是foreach包中的foreach)。 https://beckmw.wordpress.com/2014/01/21/a-brief-foray-into-parallel-processing-with-r/在R中并行处理的foreach(foreach包)
我的原代码:
library(foreach)
library(doParallel)
set.seed(10)
x = rnorm(1000)
y = rnorm(1000)
n = length(x)
nexp = 10000
perm.stat1 = numeric(n)
ptm = proc.time()
for (i in 1:nexp){
y = sample(y)
perm.stat1[i] = cor(x,y,method = "pearson")
}
proc.time()-ptm
# 1.321 seconds
然而,当我用foreach循环,我得到的结果要慢得多:
cl<-makeCluster(8)
registerDoParallel(cl)
perm.stat2 = numeric(n)
ptm = proc.time()
perm.stat2 = foreach(icount(nexp), .combine=c) %dopar% {
y = sample(y)
cor(x,y,method = "pearson")
}
proc.time()-ptm
stopCluster(cl)
#3.884 seconds
这是为什么我从下面的说明发生了什么?我做错了什么? 谢谢