优化R中嵌套的foreach dopar

时间:2016-12-26 20:10:00

标签: r foreach plyr doparallel

我想了解下面的代码是如何构建的。想知道是否需要以不同的方式组织以更快地执行。具体来说,我是否需要在嵌套循环中以不同方式使用 foreach dopar 。目前,内循环是大部分工作(ddply有1-8个故障变量,每个变量有10-200个级别),这就是我并行运行的。为简单起见,我省略了代码细节。

有什么想法吗?我的代码如下所示,确实有效,但在6核41GB的机器上需要几个小时。数据集不是那么大(<20k记录)。

for(m in 1:length(Predictors)){  # has up to three elements in the vector

  # construct the dataframe based on the specified predictor
  # subset the original dataframe based on the breakdown variables, outcome, predictor and covariates

  for(l in 1:nrow(pairwisematrixReduced)){  # this has 1-6 rows;subset based on correct comparison groups

    # some code here

    cl <- makeCluster(detectCores())  
    registerDoParallel(cl) 

    for (i in 1:nrow(subsetting_table)){  # this table has about 50 rows

      # this uses the columns specified by k in the glm; the prior columns will be used as breakdown variables
      # up to 10 covariates
      result[[length(result) + 1]] <- foreach(k = 11:17, .packages=c('plyr','reshape2', 'fastmatch')) %dopar% {   

        ddply( 
          df,
          b,   # vector of breakdown variables
          function(x) { 

           # run a GLM and manipulate the output

          ,.parallel = TRUE) # close ddply
      } # close k loop -- set of covariates
    } # close i loop -- subsetting table
  } #close l -- group combinations
} # close m loop - this is the pairwise predictor matrix 

stopCluster(cl)
result <- unlist(result, recursive = FALSE)
tmp2<-do.call(rbind.fill, result)

1 个答案:

答案 0 :(得分:4)

复制出vignette("nested")

  

3使用%:%with%dopar%

     

当并行化嵌套for循环时,始终存在要并行化的循环的问题。标准建议是......

您还在使用foreach %dopar%以及ddply.parallel=TRUE。使用六核处理器(可能是超线程)意味着foreach块将启动12个环境,然后ddply将在144个同时环境中的每个环境中启动12个环境。 foreach应更改为%do%,以便与您并行运行内循环的问题文本保持一致。或者为了使其更清晰,请将其更改为foreach并将%dopar%更改为一个循环,将%:%更改为另一个循环。

相关问题