为什么我的 R 代码在使用 foreach 时不是并行 CPU

问题描述

我有一个很长的代码,所以我用“foreach”将它们包裹起来以并行多cpu。但看起来只有 1 个 cpu 内核在忙于运行。

enter image description here

这是我的代码

library(doParallel)  
library(foreach)
no_cores <- detectCores() - 2             # leave 2 core2 for the system
registerDoParallel(cores = no_cores)  

ReadList <- read_excel("E:xxxx")
foreach(Index = 1:nrow(ReadList)) %do% { 
 # code body part is huge
 write.table(D.results,quote = FALSE,sep = " ",paste(outputpath,"Daily_",List$Gid[Index],".txt",sep=""))   # I output result for each Index within the loop
}

解决方法

就像@coletl 所说的,如果您希望 foreach 并行运行,您需要将 %do% 更改为 %dopar%

library(doParallel)  
library(foreach)
no_cores <- detectCores() - 2             # leave 2 core2 for the system
registerDoParallel(cores = no_cores)  

ReadList <- read_excel("E:xxxx")
foreach(Index = 1:nrow(ReadList)) %dopar% { 
 # code body part is huge
 write.table(D.results,quote = FALSE,sep = " ",paste(outputpath,"Daily_",List$Gid[Index],".txt",sep=""))   # I output result for each Index within the loop
}