运行 R 中并行的 for 循环
run a for loop in parallel in R
我有一个类似这样的 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)
注意 - 我必须添加一个注意事项,如果用户分配了太多进程,则用户可能会收到此错误: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/
我有一个类似这样的 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)
注意 - 我必须添加一个注意事项,如果用户分配了太多进程,则用户可能会收到此错误: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/