繁体   English   中英

在r中同时(并行)在后台运行多个作业

[英]running multiple jobs in background at same time (parallel) in 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) 

我知道在unix中,“&”通常允许作业在后台运行。 R中是否有类似的方式

您可以使用mclapplyclusterApply并行启动多个函数。 它们实际上不在后台: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)

我有很好的经验使用plyr包功能和snow创建的并行后端。 博客文章中,我描述了如何做到这一点。 在R 2.14之后并行处理是通过parallel包的R核分发的一部分。 我没有试图让plyr使用parallel生成的后端,但我认为这应该有效。

暂无
暂无

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

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