[Rcpp-devel] Using pointers with Numeric Vectors

Alon Honig honeyoak at gmail.com
Thu Dec 20 19:34:40 CET 2012


Thank you JJ, that makes sense. I had no idea that R could be so taxing
when bench-marking.

On Thu, Dec 20, 2012 at 1:27 PM, JJ Allaire <jj.allaire at gmail.com> wrote:

> It's possible that the overhead of making R function calls is swamping all
> of the other performance data here. I've re-written the example w/
> sourceCpp and with the calls to the C++ version happening inside C++ rather
> than R. This yields more like 100:1 speedup:
>
> #include <Rcpp.h>
> using namespace Rcpp;
>
> double get_var(const 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(const NumericVector& v,int l) {
>    double s = 0;
>    for (int i = 0; i <l;i++) {
>       s += v[i];
>    }
>    return(s);
> }
>
> // [[Rcpp::export]]
> double rcppVar(const NumericVector& v) {
>    int n = v.size();
>    double v_mean =  get_sum(v,n)/n;
>    double v_var = get_var(v,v_mean,n);
>    return v_var;
> }
>
> // [[Rcpp::export]]
> void callRcppVar(const NumericVector& v) {
>    for (int i=0; i<100; i++)
>       rcppVar(v);
> }
>
>
> /*** R
> a=1:1000000
> system.time(callRcppVar(a))
> system.time(for (i in 1:100) var (a))
> */
>
> > a=1:1000000
>
> > system.time(callRcppVar(a))
>    user  system elapsed
>   0.003   0.001   0.005
>
> > system.time(for (i in 1:100) var (a))
>    user  system elapsed
>   0.591   0.128   0.719
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20121220/c10cbb35/attachment-0001.html>


More information about the Rcpp-devel mailing list