为什么这个简单化的cpp函数版本变慢? [英] Why is this simplistic cpp function version slower?

查看:85
本文介绍了为什么这个简单化的cpp函数版本变慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下此比较:

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返回的某些数据转换或数据复制?

cppFun seems slower than RFun. Why is it so? Do the times for calling the functions differ? Or is it the function itself that differ in running time? Is it the time for passing and returning arguments? Is there some data conversion or data copying I am unaware of when the data are passed to (or returned from) cppFun?

推荐答案

正如上面的评论所指出的那样,这根本不是一个恰当或深思熟虑的问题.

This simply is not a well-posed or thought-out question as the comments above indicate.

一个空函数的假定基准根本不是一个.通过cppFunction()等人创建的每个函数都将调用一个R函数某些C ++函数接口.因此,这根本不可能相等.

The supposed baseline of an empty function simply is not one. Every function created via cppFunction() et al will call one R function interfacing to some C++ function. So this simply cannot be equal.

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

Here is a slightly more meaningful comparison. For starters, let's make the R function complete with curlies. Second, let's call another compiler (internal) function:

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调用ANY编译函数是有代价的.

On my box, I see a) a closer gap between versions 1 and 2 (or the C++ function) and b) little penalty over the internal function. But calling ANY compiled function from R has cost.

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

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

As we say in the real world: there ain't no free lunch.

这篇关于为什么这个简单化的cpp函数版本变慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆