[Rcpp-devel] R.e. Speed gain assistance (Wray, Christopher)
Christian Gunning
xian at unm.edu
Thu Aug 18 10:14:11 CEST 2011
There's a number of things going on in your example. Are you sure
that sample() is the bottleneck? You might want to try breaking this
into smaller pieces and benchmarking each with rbenchmark.
On Wed, Aug 17, 2011 at 3:00 AM,
<rcpp-devel-request at r-forge.wu-wien.ac.at> wrote:
>
> I have thought (but not tried) importing R's sample function...but I suspect this may be a totally rude idea.
Pulling R functions into a C++ function isn't hard, but there's
overhead -- if i recall correctly, it's appreciably slower than the
API.
Take a look at this (unweighted) sample() function. It's giving R a
run for it's money, and is pretty fast even for very large n, and it
looks statistically correct (not sure if I'm glossing over ugly,
machine-specific details of double->int conversion here). Does this
shed any light on your question?
best,
Christian
library(inline); library(Rcpp);
src1<-'
NumericVector xx(x);
int xx_sz = xx.size()-1; // index of last xx
int nn=as<int>(n);
NumericVector ret(nn);
RNGScope scope;
for (int i=0; i<nn; i++) {
ret[i] = xx[Rf_runif(0.0,xx_sz)];
};
return(ret);
'
mysample<-cxxfunction( signature(x='numeric', n="numeric"), src1, plugin='Rcpp')
system.time(result <- mysample(1:50, 1e7))
system.time(resultR <- sample(1:50, 1e7, replace=T))
--
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
More information about the Rcpp-devel
mailing list