jon*_*jon 5 parallel-processing r
我想运行一个需要大量时间的程序.我想写一个可以并行运行的函数(我是windows中的图形界面用户).该功能将任务划分为n个子任务并执行最终的共识任务.我想并行运行n任务(同一程序窗口内同时),然后组合输出.以下只是一个例子:
ptm <- proc.time()
j1 <- cov(mtcars[1:10,], use="complete.obs") # job 1
j2 <- cov(mtcars[11:20,], use="complete.obs") # job 2
j3 <- cov(mtcars[21:32,], use="complete.obs") # job 3
proc.time() - ptm
out <- list (j1 = j1, j2 = j2, j3 = j3)
Run Code Online (Sandbox Code Playgroud)
我知道在unix中,"&"通常允许作业在后台运行.R中是否有类似的方式
您可以使用mclapply或clusterApply
并行启动多个功能.它们实际上不在后台:R将等到它们全部完成(就好像你wait在Unix shell中一样,在后台启动进程后).
library(parallel)
tasks <- list(
job1 = function() cov(mtcars[1:10,], use="complete.obs"),
job2 = function() cov(mtcars[11:20,], use="complete.obs"),
job3 = function() cov(mtcars[21:32,], use="complete.obs"),
# To check that the computations are indeed running in parallel.
job4 = function() for (i in 1:5) { cat("4"); Sys.sleep(1) },
job5 = function() for (i in 1:5) { cat("5"); Sys.sleep(1) },
job6 = function() for (i in 1:5) { cat("6"); Sys.sleep(1) }
)
# Using fork()
out <- mclapply(
tasks,
function(f) f(),
mc.cores = length(tasks)
)
# Equivalently: create a cluster and destroy it.
# (This may work on Windows as well.)
cl <- makeCluster( length(tasks) )
out <- clusterApply(
cl,
tasks,
function(f) f()
)
stopCluster(cl)
Run Code Online (Sandbox Code Playgroud)