[Rcpp-devel] R.e. Speed gain assistance (Wray, Christopher)

Wray, Christopher christopher.wray.10 at ucl.ac.uk
Thu Aug 18 12:19:00 CEST 2011


Hi - thanks. Sure, my description was not very good. I suppose its a nested sample - of a sample - with an operation (+) inbetween....(and a function call...).

Suggestion was useful though, thanks. So..I can shave off 5 seconds (from a total of 20-ish) by chucking away
floor, amending runif and just making sure I am not introducing anything 'biased' via the convert.

I know that R 'converts' floating values for index positions...but (for some reason) I did not think to check that in works like that for NumericVector..too.
...I'll take the 5 seconds regardless! :-) ta, chris.

________________________________________
From: icos.atropa at gmail.com [icos.atropa at gmail.com] on behalf of Christian Gunning [xian at unm.edu]
Sent: 18 August 2011 09:14
To: rcpp-devel at r-forge.wu-wien.ac.at
Cc: Wray, Christopher
Subject: R.e. Speed gain assistance (Wray, Christopher)

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