加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

windows – 在R中的doMC和foreach循环不起作用

发布时间:2020-12-13 22:32:53 所属栏目:Windows 来源:网络整理
导读:我想在R工作中获取并行处理的foreach包,我遇到了几个问题: 在CRAN for Windows上不存在使foreach工作所需的doMC包.一些博客建议doSNOW应该做同样的工作.但是,当我使用doSNOW运行foreach命令时,%dopar%似乎不比%do%快.实际上它要慢得多.我的CPU是Intel i
我想在R工作中获取并行处理的foreach包,我遇到了几个问题:

在CRAN for Windows上不存在使foreach工作所需的doMC包.一些博客建议doSNOW应该做同样的工作.但是,当我使用doSNOW运行foreach命令时,%dopar%似乎不比%do%快.实际上它要慢得多.我的CPU是Intel i7 860 @ 2.80GHz,内存为8 GB.以下是我的代码:

##Run example in 1 core 
require(foreach)
require(doSNOW)
x= iris[which(iris[,5] != "setosa"),c(1,5)]
trials = 10000
system.time({
r= foreach(icount(trials),.combine=cbind) %do% {
ind=sample(100,100,replace=TRUE)
results1 = glm(x[ind,2]~x[ind,1],family=binomial(logit))
coefficients(results1)
}
})[3]
#  elapsed 
#  37.28 

# Same example in 2 cores
registerDoSNOW(makeCluster(2,type="SOCK"))
getDoParWorkers()
trials = 10000
system.time({
r= foreach(icount(trials),.combine=cbind) %dopar% {
ind=sample(100,family=binomial(logit))
coefficients(results1)
}
})[3]
# elapsed 
#  108.14

我重新安装了所有需要的软件包,但仍然存在同样的问题.这是输出:

sessionInfo()

#R version 2.15.1 (2012-06-22) 
#Platform: i386-pc-mingw32/i386 (32-bit)

#locale:
#[1] LC_COLLATE=English_United States.1252 
#[2] LC_CTYPE=English_United States.1252   
#[3] LC_MONETARY=English_United States.1252
#[4] LC_NUMERIC=C                          
#[5] LC_TIME=English_United States.1252    

#attached base packages:
#[1] parallel  stats     graphics  grDevices datasets  utils     methods  
#[8] base     

#other attached packages:
#[1] doParallel_1.0.1 codetools_0.2-8  doSNOW_1.0.6     snow_0.3-10     
#[5] iterators_1.0.6  foreach_1.4.0    rcom_2.2-5       rscproxy_2.0-5  

#loaded via a namespace (and not attached):
#[1] compiler_2.15.1 tools_2.15.1

解决方法

在Windows中最好使用doParallel():

require(foreach)
require(doParallel)
cl <- makeCluster(6) #use 6 cores,ie for an 8-core machine
registerDoParallel(cl)

然后运行你的foreach()%dopar%{}

编辑:OP提到仍然看到问题,所以包括我的确切代码.运行在4核Windows7 VM上,R 2.15.1 32位,只允许doParallel使用我的3个内核:

require(foreach)
require(doParallel)
cl <- makeCluster(3)
registerDoParallel(cl)

x= iris[which(iris[,5)]

trials = 1000 
system.time( 
  foreach(icount(trials),.combine=cbind) %do% 
  {  
    ind=sample(100,replace=TRUE) 
    results1 = glm(x[ind,family=binomial(logit)) 
    results1 = glm(x[ind,family=binomial(logit)) 
    coefficients(results1) 
  })[3] 

system.time( 
  foreach(icount(trials),.combine=cbind) %dopar% 
  {  
    ind=sample(100,family=binomial(logit)) 
    coefficients(results1) 
  })[3]

就我而言,%do%为17.6秒,%dopar%为14.8秒.看着任务执行,似乎大部分执行时间都是cbind,这是并行运行的常见问题.在我自己的模拟中,我做了自定义工作来保存我的详细结果作为并行任务的一部分,而不是通过foreach返回它们,以消除这部分开销.因人而异.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读