为什么我的 R 代码在使用 foreach 时不并行 CPU
why my R code is not parallel CPU when using foreach
我的代码很长,所以我用“foreach”将它们包装成并行多CPU。但看起来只有 1 CPU 个核心忙 运行。
这是我的代码:
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
}
我的代码很长,所以我用“foreach”将它们包装成并行多CPU。但看起来只有 1 CPU 个核心忙 运行。
这是我的代码:
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
}