[Rcpp-devel] First foray into Rcpp and comparison of speed with R

Dirk Eddelbuettel edd at debian.org
Thu Sep 1 18:21:23 CEST 2011


On 1 September 2011 at 17:59, Gregor GORJANC wrote:
| Hi,
| 
| On 1 September 2011 17:35, Dirk Eddelbuettel <edd at debian.org> wrote:
| 
|     ... I kind of hoped for more, but given that I vectorized much of R
|     | code and that computations are simple additions and multiplications I
|     wonder if
|     | I could get much more gains with Rcpp foray.
| 
|     Hard to say in general terms.  Rcpp sugar can help, Romain has hidden some
|     loop unrolling inside it and that helps in the benchmark example in the
|     Rcpp-introduction vignette (and JSS article) but it doesn't imply all sugar
|     code will be faster.
| 
| 
| OK. But can we say that C++ for() loop via Rcpp can be speed up further with
| Rcpp suger? 

I don;t think you can make an unconditional statement promising improvements
in all cases.  It'll always depend...

| Say simple sum of a vector or something simple like that. I do not
| know, but I would think not. I am correct? I do agree that it would ease the
| development and interpretability of code.

Sugar aims for more compact and expressive code. Speed sometimes comes as a
side effect.
 
|     ...
|     |   // --- Compute ---
|     |       
|     |   for(i = 1; i < nI+1; i++) {
| 
|     Careful about i=1:  C/C++ indices run from 0 to n-1.
| 
| 
| Thx for this, but it was deliberate as I rely on having zero in the "first"
| row.

Ack.
| 
|     |     for(t = 0; t < nT; t++) {
|     |       pa(i, t) = c1 * ped(ped(i, 1), t+3) +
|     |                  c2 * ped(ped(i, 2), t+3);
|     |     
|     |       w(i, t) = ped(i, t+3) - pa(i, t);
| 
|     The recursive nature may make it tricky to vectorise this.
| 
| 
| I thought so, but wanted to ask the experts.
| 
| 
|     ...
|     |   // --- Return ---
|     |       
|     |   Rcpp::List ret;
|     |   ret["pa"] = pa;
|     |   ret["w"]  = w;
|     |   ret["xa"] = xa;
|     |   return(ret);
| 
|     We usually do
| 
|      Rcpp::List ret = Rcpp::List::create(Rcpp::Named("pa", pa),
|                                          Rcpp::Named("w", w);
|                                          Rcpp::Named("xa", xa));
|      return ret;
| 
|     to avoid re-allocation.  But that is minuscule, and your code is arguably
|     as easy or easier to read :)
| 
| 
| Did I understand correctly that your proposal is to create return object all in
| one spot to avoid changing it as I did three times?

Yup!
 
| Thx for replies and so neat way to use so powerfull tools in R!!!

Our pleasure.

Dirk

-- 
Two new Rcpp master classes for R and C++ integration scheduled for 
New York (Sep 24) and San Francisco (Oct 8), more details are at
http://dirk.eddelbuettel.com/blog/2011/08/04#rcpp_classes_2011-09_and_2011-10
http://www.revolutionanalytics.com/products/training/public/rcpp-master-class.php


More information about the Rcpp-devel mailing list