首页 文章

R:使用doParallel和foreach进行并行化

提问于
浏览
1

我在R中做了以下连续的小例子:

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循环,因为我没有找到支持并行while循环的包 . 现在我试过这个:

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循环不允许重新定义计数器号,对吗?是否有更好的包或替代循环来并行化第一个例子?

最好的问候,布莱恩

1 回答

  • 1

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

相关问题