我想运行一个需要大量时间的程序。我想编写一个可以并行运行的函数(我是 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)
我知道在 unix 中“&”通常允许作业在后台运行。 R中是否有类似的方式
最佳答案
您可以使用 mclapply
或 clusterApply
并行启动多个功能。
他们并不是真正的背景:
R 会等到它们全部完成
(就像您在 Unix shell 中使用 wait
一样,
在后台启动进程后)。
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)
关于r - 在 r 中同时(并行)在后台运行多个作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10815622/