cfunction は,様々な言語によるコードをインラインで R の関数にしてくれる。
対応している言語は "C++", "C", "Fortran", "F95", "ObjectiveC", "ObjectiveC++"。
FORTRAN も含まれているのが私にとっては懐かしい。
code <- "
integer i
do 10 i = 2, n(1)
x(i) = x(i-1)+x(i)
10 continue
"
fun <- cfunction(signature(n="integer", x="numeric"), code, convention=".Fortran")
ただ,計算内容によっては,R の関数の方が速い場合があるので,注意が必要。
実行結果
> n <- 10000000
> x <- rnorm(n)
> system.time(a <- cumsum(x))
ユーザ システム 経過
0.104 0.000 0.104
> system.time(b <- fun(n, x)$x)
ユーザ システム 経過
0.180 0.003 0.182
> all.equal(a, b)
[1] TRUE
前の記事のプログラミング例を FORTRAN でやってみると,計算時間は同じくらいになる。
> code <- "
+ integer i, j
+ do 10 i = 1, nx(1)
+ do 20 j = 1, ny(1)
+ z(i+j-1) = z(i+j-1)+x(i)*x(j)
+ 20 continue
+ 10 continue
+ "
> fun3 <- cfunction(signature(nx="integer", x="integer", ny="integer", y="integer", nz="integer", z="integer"), code, convention=".Fortran")
> system.time(ans <- fun3(1000, x, 1000, y, 1999, z))
ユーザ システム 経過
0.001 0.000 0.002
> all.equal(ans$z, a)
[1] TRUE