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
?
First install foreach
and doParallel
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, ...
After registerDoParallel
, you can use any another function you want like below.
foreach::foreach(i=1:2) %dopar% {
test1(x)
test2(x)
test3(x)
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.