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

Why is this simplistic cpp function version slower?

考虑这个比较:

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

cppFun 似乎比 RFun 慢。为什么会这样?调用函数的时间是否不同?还是函数本身在 运行 时间上有所不同?是时候传递和返回参数了吗?是否有一些数据转换或数据复制我不知道何时将数据传递到(或返回)cppFun?

正如上面的评论所表明的,这根本不是一个恰当的或深思熟虑的问题。

空函数的假定基线根本不是一个。通过 cppFunction() 等创建的每个函数都将调用 一个 R 函数 接口到 一些 C++ 函数 。所以这根本不可能相等。

这里稍微比较有意义。对于初学者,让我们用卷曲来完成 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))

在我的盒子上,我看到 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

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