首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R:用doParallel和foreach并行化

R:用doParallel和foreach并行化
EN

Stack Overflow用户
提问于 2017-07-01 23:13:01
回答 1查看 458关注 0票数 1

我在R中做了以下顺序的mini示例:

代码语言:javascript
复制
all_list <- list()
all_list[1] <- list(1:6000)
all_list[2] <- list(100000:450000)
all_list[3] <- list(600000:1700000)
all_list[4] <- list(2000000:3300000)
all_list[5] <- list(3600000:5000000)

find <- list(c(12800, 12800, 12800, 25600, 51200, 102400, 204800, 409600, 819200, 1638400, 1638400, 2457600, 3276800, 4096000, 4915200, 4915200))
result <- list()
index <- 1
current_Intervall <- 1
current_number <- 1

while(current_number <= 5000000){

  for(i in 1:length(find[[1]])){
    if(current_number == find[[1]][i]){
      result[[index]] <- current_number
      index <- index + 1
      break
    }
  }

  current_number <- current_number + 1
  last <- lengths(all_list[current_Intervall])
  if(current_number > all_list[[current_Intervall]][last]){
    if(current_Intervall == length(all_list)){
      break
    }else{
      current_Intervall <- current_Intervall + 1
      current_number <- all_list[[current_Intervall]][1]
    }
  }
  print(current_number)
}

我想让这段代码与Windows并行。我想到了doParallel包和foreach循环,因为我没有找到一个包,它支持并行which循环。现在我试过了:

代码语言:javascript
复制
library(doParallel) 


all_list <- list()
all_list[1] <- list(1:6000)
all_list[2] <- list(100000:450000)
all_list[3] <- list(600000:1700000)
all_list[4] <- list(2000000:3300000)
all_list[5] <- list(3600000:5000000)

find <- list(c(12800, 12800, 12800, 25600, 51200, 102400, 204800, 409600, 819200, 1638400, 1638400, 2457600, 3276800, 4096000, 4915200, 4915200))
result <- list()
index <- 1
current_Intervall <- 1
current_number <- 1


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

print(current_number)

foreach(current_number=1:5000000) %dopar% {
  for(i in 1:length(find[[1]])){
    if(current_number == find[[1]][i]){
      result[[index]] <- current_number
      index <- index + 1
      break
    }
  }

  # current_number <- current_number + 1
  last <- lengths(all_list[current_Intervall])
  if(current_number > all_list[[current_Intervall]][last]){
    if(current_Intervall == length(all_list)){
      break
    }else{
      current_Intervall <- current_Intervall + 1
      current_number <- all_list[[current_Intervall]][1]
    }
  }
  print(current_number)
}

stopCluster(cl)

但是,打印输出不会打印任何内容,大约2分钟后,循环不会终止。但连续的例子在几秒钟后就成立了。我觉得有点不对劲。

另一个问题是:在foreach循环中可以重新定义计数器号吗?在上面的while循环中,我可以设置计数器"current_number“任意设置。但我认为在R中,for循环不允许重新定义计数器数,对吗?是否有更好的包或替代循环来并行第一个示例?

向你问好,布劳恩

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-02 09:41:53

如果要在使用并行性时输出某些内容,请使用makeCluster(no_cores, outfile = "")

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44866157

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档