【问题标题】:R How to get total CPU time with foreach?R如何使用foreach获得总CPU时间?
【发布时间】:2016-09-26 22:57:49
【问题描述】:

我正在尝试获取并行运行的代码的总 CPU 小时数(使用包 doParallel 中的 foreach),但我不确定如何执行此操作。我使用了proc.time(),但它只是返回“实时”时间的差异。根据我对system.time() 的阅读,它也应该与proc.time() 做同样的事情。如何获得并行运行的 R 代码的总 CPU 小时数?

【问题讨论】:

    标签: r time parallel-foreach cpu-time


    【解决方案1】:

    一个小技巧是通过list 将测量的运行时间与计算结果一起返回。如下示例,我们使用system.time() 来获得与proc.time() 相同的运行时。

    注意:这是我的博客文章 R with Parallel Computing from User Perspectives 的修改示例。

    # fake code to show how to get runtime of each process in foreach
    library(foreach)
    library(doParallel)
    
    # Real physical cores in my computer
    cores <- detectCores(logical = FALSE)
    cl <- makeCluster(cores)
    registerDoParallel(cl, cores=cores)
    
    
    system.time(
      res.gather <- foreach(i=1:cores, .combine='list') %dopar%
      {  
        s.time <- system.time( {
        set.seed(i)
        res <- matrix(runif(10^6), nrow=1000, ncol=1000)
        res <- exp(sqrt(res)*sqrt(res^3))
        })
        list(result=res, runtime=s.time)
      }
    )
    
    
    stopImplicitCluster()
    stopCluster(cl)
    

    因此,运行时保存在res.gather 中,您可以轻松获取它。所以,把它们加起来,我们就可以知道你的并行程序总共需要多少时间。

    > res.gather[[1]]$runtime
       user  system elapsed 
       0.42    0.04    0.48 
    > res.gather[[2]]$runtime
       user  system elapsed 
       0.42    0.03    0.47 
    > res.gather[[2]]$runtime[3] + res.gather[[2]]$runtime[3]
    elapsed 
       0.94 
    

    最后,2 个 R 会话的运行时间为 0.94 秒,不考虑 R 主控的等待时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多