【R】microbenchmarkの使い方

Rで実行時間を比較する際にmicrobenchmarkを使うと便利です。もちろんドキュメントはありますが、日本語でまとまった情報が無かったので作りました。
ドキュメント(https://cran.r-project.org/web/packages/microbenchmark/microbenchmark.pdf)
基本構文
library(microbenchmark)
microbenchmark(変数 = ベンチマークしたい処理) #変数名を指定しない時は入力されたコマンドのまま表示されますオプションの指定は少ないと思いますが、以下のように指定できます(ドキュメントから)。
- list: List of unevaluated expressions to benchmark.
- times: Number of times to evaluate each expression.
- unit: Default unit used in summary and print.
- check: A function to check if the expressions are equal. By default NULL which omits the check. In addition to a function, a string can be supplied. The string ‘equal’ will compare all values using all.equal, ‘equivalent’ will compare all values using all.equal and check.attributes = FALSE, and ‘identical’ will compare all values using identical.
- control: List of control arguments. See Details.
- setup: An unevaluated expression to be run (untimed) before each benchmark expression.
複数の処理を比較する場合
microbenchmark(
 変数1 = 処理1, #複数の処理をベンチマークする場合はカンマで区切る
 変数2 = 処理2,
 変数3 = 処理3  #最後は不要
)複数のコマンドを合わせた処理の場合は{ }でくくって入力します。
使用例(差分計算の時間計測から)
mbench <- microbenchmark(
#forで差分計算(力業)
  "for" = {
    n <- 1
    x <- NA
    for( n in 1:i ){
      if (n == 1){
        x <- Dataset[n, 1]
      }else{
        Dataset[n, "diff_for"] <- Dataset[n, 1] - x
        x <- Dataset[n, 1]
      }
    }
  },
#diffで差分計算
  "diff" = Dataset$diff_diff <- append(NA, diff(Dataset$V1)),
#dplyrで差分計算
  "lag" = Dataset$diff_dplyr <- Dataset$V1 - dplyr::lag(Dataset$V1)
)
#箱ひげ図作成
plot(mbench)
#ベンチマーク結果の一覧表示
mbench出力
Plot(箱ひげ図)

見づらい場合はPlotのスケール等を指定してください。
結果
Unit: microseconds
 expr    min      lq      mean  median      uq     max neval cld
  for 8669.2 9309.70 10249.202 9751.90 10476.6 17528.7   100   b
 diff   14.5   19.65    45.687   27.35    37.6  1521.1   100  a 
  lag   43.8   62.80   107.382  110.80   123.7   289.5   100  a (おまけ)変数を使わない場合
変更点
#diffで差分計算
  #"diff" = Dataset$diff_diff <- append(NA, diff(Dataset$V1)),
  Dataset$diff_diff <- append(NA, diff(Dataset$V1)),
#dplyrで差分計算
  #"lag" = Dataset$diff_dplyr <- Dataset$V1 - dplyr::lag(Dataset$V1)
  Dataset$diff_dplyr <- Dataset$V1 - dplyr::lag(Dataset$V1)結果
Unit: microseconds
                                                      expr    min
                                                       for 8253.1
         Dataset$diff_diff <- append(NA, diff(Dataset$V1))   14.5
 Dataset$diff_dplyr <- Dataset$V1 - dplyr::lag(Dataset$V1)   43.4
      lq     mean median      uq     max neval cld
 8685.20 9633.174 8967.1 9605.00 17018.9   100   b
   18.35   41.969   27.6   36.30  1384.7   100  a 
   59.75   94.788   99.4  115.45   230.7   100  a 短いコマンドはどちらでもいいですが、変数にする方が見やすいとは思います。

















ディスカッション
コメント一覧
まだ、コメントがありません