【问题标题】:why my R code is not parallel CPU when using foreach为什么我的 R 代码在使用 foreach 时不是并行 CPU
【发布时间】:2021-05-23 12:29:48
【问题描述】:

我的代码很长,所以我用“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
}

【问题讨论】:

标签: r foreach parallel.foreach doparallel


【解决方案1】:

就像@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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    相关资源
    最近更新 更多