【问题标题】:Passing objects via clusterExport or as function arguments通过 clusterExport 或作为函数参数传递对象
【发布时间】:2022-08-17 19:07:03
【问题描述】:

将对象作为函数参数传递给parallel::parLapplyparallel::parLapplyLB 还是使用parallel::clusterExport 导出它们更有效? IE。

parallel::parLapply(cl, 1:1000, function(y, x1, x2, x3, x4, x5) {
  ...
}, x1, x2, x3, x4, x5)

或者

parallel::clusterExport(cl, c(\"x1\", \"x2\", \"x3\", \"x4\", \"x5\"))
parallel::parLapply(cl, 1:1000, function(y) {
  ...
})

非并行函数,例如默认情况下不复制传递给它们的参数。它们仅在修改对象时创建副本。我想知道,上述两个并行选项在避免不必要的对象复制方面是否有不同的优势。

  • 您使用的是哪个操作系统?要共享数据,您需要makeCluster 才能FORK 进程。不幸的是,Windows only allows PSOCK,这意味着数据无论如何都会被复制到每个工作人员,您考虑的两个选项之间几乎没有区别。
  • 我使用的是 Windows 机器,因此使用了PSOCK。即使它在这种情况下复制数据,问题中提到的两种方法是否以不同的效率处理它?那么FORK 案例呢? FORK 集群哪个选项更有效?

标签: r parallel-processing rparallel


【解决方案1】:

对于您的两个版本的大型数据集,我遇到了内存管理困难。我可以建议:

par_func <- function(my_list, x1, x2, x3, x4, x5, ncores){
  # A function to use in the parallel loop
  loop_fun <- function(x){
    # x is i. element in the list
    tryCatch({
      foo(x, x1, x2, x3, x4, x5) # the actual function which would do the work
    }, error = function(err){
      #error_case <- foo2(x, x1, x2, x3, x4, x5) # in case something goes wrong foo2 will deliver something
      error_case <- NULL  # or it can also just return NA or NULL instead of a function's output to prevent error
      return(error_case)
      })
  }
  cl <- parallel::makeCluster(ncores)
  x1 <- x1
  x2 <- x2
  x3 <- x3 
  x4 <- x4 
  x5 <- x5
  out <- parallel::parSapplyLB(cl = cl, 
                               X = my_list,
                               FUN = function(x) loop_fun(x)
                               )
  return(out)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 2018-02-23
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多