我有一个类似这样的 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)
}
最佳答案
感谢您的反馈。在发布这个问题后,我确实查了一下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)
注意 - 我必须添加一条注释,如果用户分配太多进程,则用户可能会收到此错误:序列化错误(数据,node$con):写入连接时出错
注意 - 如果 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/
关于在 R 中并行运行 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38318139/