[Rcpp-devel] Using pointers with Numeric Vectors
Alon Honig
honeyoak at gmail.com
Thu Dec 20 18:35:31 CET 2012
My current RCPP program is only 4 times faster than its R byte code
compiled equivalent. I am trying to speed up my code and from what I
understand using pointers prevents an external function from copying the
entire object when executing its methods. I am having difficulty finding
salient examples that use points and NumericVectors. Please tell me how in
this same code I could get the functions "get_sum" and "get_var" to point
to the NumericVector object "v" rather than copy the whole thing.
library(inline)
library(Rcpp)
a=1:1000000
Rcpp.var = cxxfunction(signature(input="numeric"), plugin="Rcpp",
body="
NumericVector v = input;
int n = v.size();
double v_mean = get_sum(v,n)/n;
double v_var = get_var(v,v_mean,n);
return wrap(v_var);
",includes="
double get_var(NumericVector v,double m,int l)
{double a = 0;
for (int i = 0; i <l;i++)
{a += (v[i]-m)*(v[i]-m);}
return(a/l);
}
double get_sum(NumericVector v,int l)
{ double s = 0;
for (int i = 0; i <l;i++)
{s += v[i];}
return(s);
}
")
b=system.time(for (i in 1:100)Rcpp.var (a))
c= system.time(for (i in 1:100)var (a))
Thank you Alon.
P.S. I am aware that the "get_var" function provides the population
variance and not the sample variance.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20121220/70685a34/attachment.html>
More information about the Rcpp-devel
mailing list