Rの並列化(doSNOW)

doSNOWパッケージを用いて指定したCPUコア数にタスクを分割
foreachパッケージを用いて処理を並列化

library(doSNOW)
## Loading required package: foreach
## Loading required package: iterators
## Loading required package: codetools
## Loading required package: snow
N <- 10^4
cores <- 1:8
r <- rep(NA, length(cores))
for (i in cores) {
    cl <- makeCluster(i, type = "SOCK")
    registerDoSNOW(cl)
    r[i] <- system.time(foreach(i = 1:N, .combine = "c") %dopar% mean(rnorm(N)))[3]
    stopCluster(cl)
}

plot(cores, r/r[1], type = "b", xlab = "number of cores", ylab = "relative time compared with single core")
abline(v = 4, lty = 4, col = "red")
title(main = "Parallel computing by doSNOW + foreach")

plot of chunk unnamed-chunk-1

print(data.frame(cores, time = r, relative = r/r[1]))
##   cores  time relative
## 1     1 32.69   1.0000
## 2     2 19.51   0.5968
## 3     3 15.09   0.4617
## 4     4 13.70   0.4191
## 5     5 13.78   0.4215
## 6     6 14.62   0.4473
## 7     7 14.99   0.4585
## 8     8 14.99   0.4586