R での並列プログラミングでいくつかの基本的なことを試しています。結果は非常に一貫性がありません。
私の最初の手法は、「並列」ライブラリの parSapply() 関数を使用することでした。結果は一貫しています。並列プロセスにコアを追加すると、速度が著しく向上します。
library(parallel)
# Initiate test list
testlist <- 2:10000000
# Initiate test function
testfunction <- function(x) {
c(x, x^2, x^3)
}
# Calculate the number of cores
no_cores <- detectCores()
# Initiate cluster
cl <- makeCluster(no_cores)
clusterExport(cl, "testlist")
# Execute things
system.time(parSapply(cl, testlist, testfunction))
# Close cluster
stopCluster(cl)
ただし、2 番目の方法では、「foreach」パッケージの foreach() 関数を使用します。その結果は一貫していません。1 コアではなく 2 コアを使用すると、速度が向上します。しかし、3コアや4コアを使っても改善されません。なぜこうなった?
library(parallel)
library(foreach)
library(doParallel)
# Initiate test list
testlist <- 2:100000
# Initiate test function
testfunction <- function(x) {
c(x, x^2, x^3)
}
# Initiate separate parallel function
parallelfunction <- function(x) {
foreach(x = testlist, .combine = c, .export = "testfunction") %dopar% {
testfunction(x)
}
}
# Calculate the number of cores
no_cores <- detectCores() - 3
# Create an implicit cluster
registerDoParallel(no_cores)
# Do things
system.time(parallelfunction())
gc()
# Stop implicit cluster
stopImplicitCluster()
「no_cores」の値を変更してテストします。(つまりno_cores <- detectCores() - x
)。リストのサイズはこれに違いはありませんでした。