コースへようこそ

Rcpp で R コードを最適化する

Romain François

Consulting Datactive, ThinkR

R vs C++

R

  • 柔軟で優れた言語
  • 低速
  • インタープリタ型

C++

  • コンパイル型
  • 習得が難しい
  • 高速
Rcpp で R コードを最適化する

動機

  • Rcppを使ってコードを高速化
  • C++の全知識は不要
  • シンプルなC++関数の作成に集中
Rcpp で R コードを最適化する

コース構成

  • 導入 — 基本的なC++構文
  • C++の関数と制御フロー
  • ベクタークラス
  • ケーススタディ
Rcpp で R コードを最適化する

パフォーマンスの測定

maxのループ版

slowmax <- function(x){
   res <- x[1]
   for ( i in 2:length(x) ){
       if( x[i] > res ) res <- x[i]}
   res  }

microbenchmarkを使ったパフォーマンス比較

library(microbenchmark)

x <- rnorm(1e6)
microbenchmark( slowmax(x), max(x) )

 

Unit: milliseconds
       expr       min       lq      mean    median        uq       max neval
 slowmax(x) 31.649452 34.29454 36.344912 35.435299 37.188249 90.363038   100
     max(x)  1.563559  1.74036  1.939367  1.847045  2.014684  3.340052   100
Rcpp で R コードを最適化する
Rcpp で R コードを最適化する

evalCppを使ったC++式の評価

library(Rcpp)
evalCpp( "40 + 2" )
42
evalCpp( "exp(1.0)" )
2.718282
evalCpp( "sqrt(4.0)" )
2
std::numeric_limits<int>::max()

を使用して32ビット符号付き整数(int)の最大値を取得

evalCpp(
   "std::numeric_limits<int>::max()"
   )
2147483647 

( $\footnotesize \mathtt{2147483647 = 2^{31}-1}$)

Rcpp で R コードを最適化する

基本的な数値型

C++はリッチな数値型を持つ

  • 整数型: int
  • 浮動小数点型: double
Rcpp で R コードを最適化する

R

# Literal numbers are double
x <- 42
storage.mode(x)
"double"
# Integers need the L suffix
y <- 42L
storage.mode(y)

z <- as.integer(42) storage.mode(z)
"integer"
"integer"

C++

# Suffix .0 forces a double
y <- evalCpp( "42.0" )
storage.mode(y)
"double"
library(Rcpp)
# Literal integers are int
x <- evalCpp( "42" )
storage.mode(x)
"integer"
Rcpp で R コードを最適化する

キャスト

(double)を使った明示的なキャスト

# Explicit cast
y <- evalCpp("(double)(40 + 2)")
storage.mode(y)
"double"

整数除算に注意

# Integer division
evalCpp( "13 / 4" )
3

 

# Explicit cast, and hence use 
# of double division
evalCpp( "(double)13 / 4" )
3.25

 

# Automatic conversion in R
13L / 4L
3.25
Rcpp で R コードを最適化する

練習しましょう!

Rcpp で R コードを最適化する

Preparing Video For Download...