【发布时间】:2015-09-28 22:59:09
【问题描述】:
我正在使用 for 循环计算置换检验统计量。我希望使用并行处理(特别是 foreach 包中的 foreach)来加快速度。我正在按照以下说明进行操作: https://beckmw.wordpress.com/2014/01/21/a-brief-foray-into-parallel-processing-with-r/
我的原始代码:
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
为什么会这样?我做错了什么? 谢谢
【问题讨论】:
标签: r permutation parallel-processing