1

I use Rcpp and RcppArmadillo and i have a "strange" problem. Lets say that i have function f1(). I include this function inside my package and run the command "R CMD INSTALL". After it's done i run a benchmark and i realise that f1 is slower about 100 microseconds inside the package than outside. So if a function wants 100ms to finish, in the package wants about 200+ms.

Code:

functions.cpp

vec f1(vec x){
    vec F( x.size() );
    for( int i = 0; i < x.size(); ++i ){
         // do something 
    }
    return F;
}

exportfunctions.cpp

vec f1(vec x);
RcppExport SEXP MyPackage_f1(SEXP xSEXP) {
BEGIN_RCPP
    RObject  __result;
    RNGScope __rngScope;
    traits::input_parameter< vec >::type      x(xSEXP);
    __result = wrap(f1(x));
   return __result;
END_RCPP
}

exportfunctions.R

f1<- function(x) {
    .Call( ' MyPackage_f1 ' , PACKAGE = ' MyPackage ', x )
}

An example of how my code is been written. I believe the problem is that a function.R calls a function.cpp wich calls the final function. But why is this happening inside the package and not in sourceCpp. I can't understand the difference.

Manos Papadakis
  • 564
  • 5
  • 17

1 Answers1

5

Briefly:

  • 100ms is a non-issue. You are coming from R which is an interpreted environment

  • Calling a function involves several steps. Finding a function in a package involves some more.

  • See the documentation for .Call() to see how to minimize lookup.

  • See the documentation for NAMESPACE to set identifiers there too.

The latter two points should help close the gap between calling an ad-hoc function in the environment (which is cheaper) verses calling a function from the properly created infrastructure for doing so a.k.a. a package.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • I agree than is not an issue but when I sourceCp p the function it needs about 22ms and the same R's function need about 100ms for a vector of 1000 cells. Guess what happened when I call the same function from inside the package, it's slower than R's. Thats why I wonder what is happening behind. I will read the documentation about .call. thanks for the answer! – Manos Papadakis Aug 08 '16 at 12:40
  • 2
    You just restated your question again. _These are different code paths to get to your function_ and that is why the timing is different. _C'est la vie._ By the way I wasn't the one downvoting your question. – Dirk Eddelbuettel Aug 08 '16 at 13:09
  • Ok then thanks for your answer and your help. I will read the documentations. Thanks for the inform about downvoting. – Manos Papadakis Aug 08 '16 at 16:50