r - Why a self-written Rcpp vectorized mathematical function is faster than its base counterpart? -


OK, I know the answer, but due to this being motivated, I want to know some good advice about the following : Why is RCPP exercise CA down? 15% faster (for long vectors) than the built-in exp () ? We all know that Rcpp is a wrapper for R / C API, so we should expect a little worse performance than the one.

  Rcpp :: cppFunction ("NumericVector exp2" (NumericVector X) {NumericVector z = RCPP :: Clone (x); Int N = Z SEE (); for (intI = 0; I & lt; n; ++ i) Z [I] = XP (Z [I]); Return Z;} ") Library (" microbenchmark ") X & lt; - rcauchy (1000000) microbenchmark (equation (x), exp2 (x), unit = "relative") ## Unit: relative ## expr min LQ median uq max neval ## exp (x) 1,159893 1,154143 1 , 155856 1,154482 0,926272 100 100 ## exp2 (x) 1,00,000,000 1,00,000,000 1,00,000,000 1,00,000,000 1,00,000,000 100  

base r NA is used to check further, we can not do this. Also keep in mind that loop is doing tricks like unrolling (as RCpp did in Chinese), we can do a bit better still.

Then I added

  Rcpp :: cppFunction ("NumericVector expSugar (NumericVector X) {return exp (x);}")  

And with that I get another advantage - towards the user with less code:

  R & gt; Microbenchmark (consonant (x), exp2 (x), expsugar (x), unit = "relative") unit: relative expr min LQ means median uq max neval exp (x) 1,11190 1,11130 1,11718 1,10799 1,08938 1,02590 100 Exp2 (X) 1.08,184 1.08937 1.07289 1.07621 1.06382 1.00462 100 Express (X) 1.00000 1.00000 1.00000 1.00000 1.00000 1.00000 100 R & gt;  

Comments

Popular posts from this blog

c# - SignalR: "Protocol error: Unknown transport." when navigating to hub -

class - Kivy: how to instantiate a dynamic classes in python -

python - mayavi mapping a discrete colorbar on a surface -