2016-09-26 103 views
1

我想獲得並行運行代碼的總CPU小時數(使用包doParallel中的foreach),但我不確定如何去做這件事。我使用proc.time(),但它只是返回「真實」時間的差異。從我所讀到的system.time()中,它也應該和proc.time()一樣。我如何獲得並行運行的R代碼的總CPU時間?R如何使用foreach獲得總CPU時間?

回答

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主站的計費等待時間。

+0

噢,非常感謝你! – Plinth