【问题标题】:run a for loop in parallel in R在 R 中并行运行 for 循环
【发布时间】:2016-11-14 01:28:37
【问题描述】:

我有一个类似这样的 for 循环:

for (i=1:150000) {
   tempMatrix = {}
   tempMatrix = functionThatDoesSomething() #calling a function
   finalMatrix =  cbind(finalMatrix, tempMatrix)

}

你能告诉我如何使这个平行吗?

我根据在线示例尝试了此方法,但不确定语法是否正确。它也没有提高速度。

finalMatrix = foreach(i=1:150000, .combine=cbind) %dopar%  {
   tempMatrix = {}
   tempMatrix = functionThatDoesSomething() #calling a function

   cbind(finalMatrix, tempMatrix)

}

【问题讨论】:

  • 并行运行需要相当多的开销。只有在functionThatDoesSomething 花费足够的时间让开销变得值得时,您才能获得显着的加速。
  • 我认为在这篇文章合格之前你还需要做很多工作。查找parallel 和doParallel 包,例如...
  • 你不应该需要这个 -- cbind(finalMatrix, tempMatrix) -- 如果你使用 .combine 参数,只需返回函数输出。

标签: r parallel-processing parallel-foreach


【解决方案1】:

感谢您的反馈。发布此问题后,我确实查找了parallel。

最后经过几次尝试,我让它运行起来了。我添加了下面的代码以防对其他人有用

library(foreach)
library(doParallel)

#setup parallel backend to use many processors
cores=detectCores()
cl <- makeCluster(cores[1]-1) #not to overload your computer
registerDoParallel(cl)

finalMatrix <- foreach(i=1:150000, .combine=cbind) %dopar% {
   tempMatrix = functionThatDoesSomething() #calling a function
   #do other things if you want

   tempMatrix #Equivalent to finalMatrix = cbind(finalMatrix, tempMatrix)
}
#stop cluster
stopCluster(cl)

注意 - 我必须添加一个注意,如果用户分配了太多的进程,那么用户可能会得到这个错误:Error in serialize(data, node$con) : error writing to connection

注意 - 如果 foreach 语句中的 .combine 是 rbind ,则返回的最终对象将通过逐行附加每个循环的输出来创建。

希望这对像我一样第一次在 R 中尝试并行处理的人有用。

参考资料: http://www.r-bloggers.com/parallel-r-loops-for-windows-and-linux/ https://beckmw.wordpress.com/2014/01/21/a-brief-foray-into-parallel-processing-with-r/

【讨论】:

  • 我可以从并行循环中返回多个不同的对象吗?例如我想返回数据框和向量/列表?
  • @user1700890,这可能会回答你的问题stackoverflow.com/questions/19791609/…
  • 请注意,如果您在 %dopar% 循环中的代码包含来自外部包的任何函数,则您必须将 library() 调用 inside 放在循环中。跨度>
  • @mikoontz 这也可以通过 .packages 到 foreach 的参数来完成,例如foreach(i=1:150000, .combine=cbind, .packages=c("dplyr", "tidyr")) ...
  • 出于优化目的,请务必尝试比较detectCores() VS detectCores(logical = FALSE)。如果您使用所有处理器 97% 或更多,大多数时候,您的程序最喜欢使用 detectCores(logical = FALSE) 运行得更快,否则使用 detectCores()
猜你喜欢
  • 1970-01-01
  • 2013-12-12
  • 1970-01-01
  • 1970-01-01
  • 2014-04-12
  • 1970-01-01
  • 2011-01-31
  • 2019-07-03
  • 1970-01-01
相关资源
最近更新 更多