2016-09-26 2 views
1

코드의 총 CPU 시간을 병렬로 실행하려고합니다 (foreach, 패키지 doParallel에서). 그러나이 작업을 수행하는 방법을 잘 모르겠습니다. proc.time()을 사용했지만 '실제'시간의 차이 만 반환합니다. 내가 읽은 것에서 system.time()까지, 그것은 또한 proc.time()과 똑같이해야합니다. R 코드의 총 CPU 시간을 병렬로 실행하려면 어떻게합니까?R foreach를 사용하여 총 CPU 시간을 얻는 방법?

답변

1

약간의 트릭은 계산 결과와 함께 측정 된 런타임을 list으로 반환하는 것입니다. 아래 예제와 같이 과 같은 런타임을 얻으려면 system.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

관련 문제