为什么这个简单的cpp函数版本更慢?

Rem*_*i.b 0 performance benchmarking r function rcpp

考虑这种比较:

require(Rcpp)
require(microbenchmark)

cppFunction('int cppFun (int x) {return x;}')
RFun = function(x) x

x=as.integer(2)
microbenchmark(RFun=RFun(x),cppFun=cppFun(x),times=1e5)

Unit: nanoseconds
   expr  min   lq      mean median   uq      max neval cld
   RFun  302  357  470.2047    449  513   110152 1e+06  a 
 cppFun 2330 2598 4045.0059   2729 2879 68752603 1e+06   b
Run Code Online (Sandbox Code Playgroud)

cppFun似乎慢了RFun.为什么会这样?调用函数的时间有所不同吗?或者是运行时间不同的功能本身?是传递和返回参数的时间吗?是否有一些数据转换或数据复制我不知道何时将数据传递给(或从中返回)cppFun

Dir*_*tel 12

正如上面的评论所表明的那样,这根本不是一个好的或经过深思熟虑的问题.

假设空函数的基线不是一个.通过cppFunction()et al 创建的每个函数都会调用一个某些C++函数接口的R 函数.所以这根本不可能是平等的.

这是一个稍微有意义的比较.首先,让我们使用curlies完成R功能.其次,让我们调用另一个编译器(内部)函数:

require(Rcpp)
require(microbenchmark)

cppFunction('int cppFun (int x) {return x;}')
RFun1 <- function(x) { x }
RFun2 <- function(x) { .Primitive("abs")(x) }

print(microbenchmark(RFun1(2L), RFun2(2L), cppFun(2L), times=1e5))
Run Code Online (Sandbox Code Playgroud)

在我的方框中,我看到a)版本1和2(或C++函数)之间的距离越近,b)对内部函数的惩罚越小. 但是从R调用任何编译函数都需要花费.

Unit: nanoseconds
       expr min   lq     mean median   uq     max neval
  RFun1(2L) 171  338  434.136    355  408 2659984 1e+05
  RFun2(2L) 683  937 1334.046   1257 1341 7605628 1e+05
 cppFun(2L) 721 1131 1416.091   1239 1385 8544656 1e+05
Run Code Online (Sandbox Code Playgroud)

正如我们在现实世界中所说:没有免费的午餐.