LoginSignup
6
8

More than 5 years have passed since last update.

R の foreach で並列処理するとき、クラスタを implicit にする #rstatsj

Last updated at Posted at 2014-10-29

R の foreach パッケージで並列処理するとき、通常は次のように書きます。

R
library(doParallel) # foreach も読みこまれる

cl <- makeCluster(detectCores())
registerDoParallel(cl)
foreach(i = 1:3) %dopar% {
  rnorm(i)
}
stopCluster(cl)

しかし、doParallel を使う場合、もっと簡潔に書く方法が用意されています。
並列計算用のクラスタオブジェクト cl を用意せず、非明示的に処理する方法です。

R
registerDoParallel(detectCores())
foreach(i = 1:3) %dopar% {
  rnorm(i)
}
stopImplicitCluster()

registerDoParallel() の引数に直接クラスタ数を書き込みます。
クラスタの終了処理は stopImplicitCluster() で行います。

ただし、現状の stopImplicitCluster() にはバグがあり、このままでは動きません。
詳しくは次の記事を参照してください。

したがって、次のような関数 stopImplicitCluster2() を自分で書く必要があります。

R
stopImplicitCluster2 <- function() {
  options <- doParallel:::.options
  if (exists(".revoDoParCluster", where = options) &&
        !is.null(get(".revoDoParCluster", envir = options))) {
    stopCluster(get(".revoDoParCluster", envir = options))
    remove(".revoDoParCluster", envir = options)
  }
}

これを使えば、次のように並列処理を簡潔に書くことができます。

R
registerDoParallel(detectCores())
foreach(i = 1:3) %dopar% {
  rnorm(i)
}
stopImplicitCluster2()

以前の記事で紹介した on.exit() 関数を使うと、次のようになります。

R
ExecuteParallelProcess <- function() {
  registerDoParallel(detectCores())
  on.exit(stopImplicitCluster2()) 
  foreach(i = 1:3) %dopar% {
    rnorm(i)
  }
}

ExecuteParallelProcess()

以上です。

関連記事

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8