Hi list - although not strictly (or not really at all..) an Rcpp problem - I thought that since there are so many 'better-than-I' c++ coders here - whom are familiar with R... it might be a good place to ask.
I have a "naive" piece of code - that in essence replicates what the R function "sample" does. Here is a full/toy example using inline, below. My problem is this is used in part of a larger piece of code.. and it is a major bottleneck... Where I have put 50,000 in the function below - what I am really using is 10,000,000 so sscpp2(ttin,10000000,1.0,126) is the real function call. I have toyed with the idea of running all the "runifs" at once (hence the make_matrix function) but R complains about allocating large vectors..sometimes. I have also tried using std::random_shuffle (to get rid of the runifs) - although performance is then dependent upon the size of the incoming vector 'RetIn' (why shuffle all the elements when I only need some, etc). I have thought (but not tried) importing R's sample function...but I suspect this may be a totally rude idea. If anyone has time, or inclination, if they spot a dumb idea in my code - or know a better Rcpp way to do this - Id much appreciate it! Thanks, chris ________________________________ library(inline); library(Rcpp); inc<-' using namespace Rcpp; double Fn(double a, double b) { return std::max(0.0,exp(a)-b); } SEXP make_matrix(int nr, int nc, int d){ NumericVector y=floor(runif(nr*nc)*(d-1)); y.attr("dim")=Dimension(nr,nc); return y; } ' src<-' NumericVector RetIn(RetVec); int SS_C=as<int>(SamSize); double St_C=as<double>(StM); int ES_C=as<int>(ExpSize); int i,j; NumericVector OutVec=rep(0.0,SS_C),SamIndx(ES_C); RNGScope scope; //NumericMatrix SamIndx=make_matrix(SS_C,ES_C,RetIn.size()-1); for(j=0;j<SS_C;j++) { SamIndx=floor(runif(ES_C)*(RetIn.size()-1)); for(i=0; i<ES_C; i++) { OutVec[j]+=RetIn[SamIndx[i]]; } } NumericVector strVEC=rep(St_C,SS_C), ans(SS_C); std::transform(OutVec.begin(),OutVec.end(),strVEC.begin(),ans.begin(),Fn); double MeanOut=mean(ans); return(wrap(MeanOut)); ' sscpp2<-cfunction( signature(RetVec="numericVector",SamSize="numeric",StM="numeric",ExpSize="numeric"), src,inc, Rcpp=TRUE,cppargs="",convention=".Call") ttin=runif(2000)/10000 sscpp2(ttin,50000,1.0,126) #####
_______________________________________________ Rcpp-devel mailing list Rcpp-devel@lists.r-forge.r-project.org https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel