2016-09-26 8 views
1

コードの合計CPU時間を(foreach、パッケージdoParallelから)実行しようとしていますが、これを行う方法についてはわかりません。私は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セッションの実行時間は、Rマスタのアカウンティング待ち時間なしで0.94秒です。

+0

ありがとうございました! – Plinth

関連する問題