简体   繁体   English

如何并行两个或多个函数

[英]How to parallel two or more functions

If I have two or more functions with different parameters,how can I make them parallel? 如果我有两个或更多具有不同参数的函数,我该如何使它们并行? Please give me an example that is not too complicated. 请给我一个不太复杂的例子。

I only know how to parallel single function. 我只知道如何并行单功能。

 test <- function(x) {
     for (i in 1:10000000) {
         x <- x + i
     }
     return(x)
 }
 library(snow)
 cl <- makeCluster(type = "SOCK", c("localhost", "localhost"))  # 建立两个本地CPU内核的并行
 system.time({test(5);test(5)})
用户 系统 流逝 
0.58 0.00 0.58 
 system.time(clusterCall(cl, test,5)) # 测试并行循环的耗时
用户 系统 流逝 
0.00 0.00 0.37 

How about using library foreach ? 使用库foreach怎么样?

First install foreach and doParallel 首先安装foreachdoParallel

install.packages('foreach')
install.packages('doParallel')

And i edited your code a litte . 我编辑了你的代码。

test1 <- function(x) {
 for (i in 1:10000000) {
 x <- x + i
 }
 return(x)
}
library(snow)
cl <- makeCluster(type = "SOCK", c("localhost", "localhost")) 
doParallel::registerDoParallel(cl)

If you have functions like test1, test2, test3, ... 如果你有test1, test2, test3, ...等函数test1, test2, test3, ...

After registerDoParallel , you can use any another function you want like below. registerDoParallel之后,你可以使用你想要的任何其他功能,如下所示。

foreach::foreach(i=1:2) %dopar% {
test1(x)
test2(x)
test3(x)
...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM