Thank you JJ, that makes sense. I had no idea that R could be so taxing when bench-marking.<br><br><div class="gmail_quote">On Thu, Dec 20, 2012 at 1:27 PM, JJ Allaire <span dir="ltr"><<a href="mailto:jj.allaire@gmail.com" target="_blank">jj.allaire@gmail.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><font face="arial,helvetica,sans-serif">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:</font><div>
<br></div><div><div><div>#include <Rcpp.h></div><div>using namespace Rcpp;</div><div><br></div><div>double get_var(const NumericVector& v,double m,int l) {</div><div class="im"><div> double a = 0;</div><div> for (int i = 0; i <l;i++) {</div>
<div> a += (v[i]-m)*(v[i]-m);</div><div> }</div><div> return(a/l);</div><div>}</div><div><br></div></div><div>double get_sum(const NumericVector& v,int l) { </div><div class="im"><div> double s = 0;</div><div>
for (int i = 0; i <l;i++) {</div>
<div> s += v[i];</div><div> } </div><div> return(s);</div><div>}</div><div><br></div></div><div>// [[Rcpp::export]]</div><div>double rcppVar(const NumericVector& v) {</div><div class="im"><div> int n = v.size();</div>
<div> double v_mean = get_sum(v,n)/n;</div>
<div> double v_var = get_var(v,v_mean,n);</div></div><div> return v_var;</div><div>}</div><div><br></div><div>// [[Rcpp::export]]</div><div>void callRcppVar(const NumericVector& v) {</div><div> for (int i=0; i<100; i++)</div>
<div> rcppVar(v);</div><div>}</div><div><br></div><div><br></div><div>/*** R</div><div>a=1:1000000</div><div>system.time(callRcppVar(a))</div><div>system.time(for (i in 1:100) var (a))</div><div>*/</div></div></div>
<div>
<br></div><div><div>> a=1:1000000</div><div><br></div><div>> system.time(callRcppVar(a))</div><div> user system elapsed </div><div> 0.003 0.001 0.005 </div><div><br></div><div>> system.time(for (i in 1:100) var (a))</div>
<div> user system elapsed </div><div> 0.591 0.128 0.719 </div></div>
</blockquote></div><br>