[Rcpp-devel] about speed of rXXX

Dirk Eddelbuettel edd at debian.org
Thu Jan 5 15:44:41 CET 2012


On 5 January 2012 at 11:45, Gregor Kastner wrote:
| hi again,
| 
| I am currently in the process of speeding up my MCMC simulations and strongly
| consider using Rcpp. Since MCMC (naturally) heavily depends on fast RNG I was
| wondering whether anyone has tested the speed of syntactic sugar rnorm and
| friends as opposed to native C/C++ algorithms; or maybe can provide me with a
| reference?

What makes you think sugar is not native C++ wrapping native C?  It really is
"just" a template layer around the native R API, implemented in C.

Generally speaking, this stuff is sometimes hard to figure out from code---so
we often suggest to run quick benchmarks, rather than conjecturing.  We
really do believe in empirics here.

Run something like this:


library(inline)
library(rbenchmark)

nr <- function(N) rnorm(N)

nrcpp <- cxxfunction(signature(Ns="integer"), plugin="Rcpp", body='
   int n = Rcpp::as<int>(Ns);
   RNGScope tmp;                        // important for RNGs with Rcpp
   return rnorm(n);
')

res <- benchmark(nr(10000), nrcpp(10000), order="relative")[,1:5]
print(res)



which on my system just showed a 20% gain (over a tight C function called
from R) :


edd at max:/tmp$ r gregor.r 
Loading required package: methods
          test replications elapsed relative user.self
2 nrcpp(10000)          100   0.086 1.000000      0.08
1    nr(10000)          100   0.104 1.209302      0.10
edd at max:/tmp$ 


If you can make it faster still let us know :)

The one thing you do NOT want to do is to call the R function rnorm via the
Rcpp::Function (or equivalent) interface: lots of overhead.  Sugar, on the
other hand, is mean and lean.

Dirk

-- 
"Outside of a dog, a book is a man's best friend. Inside of a dog, it is too
dark to read." -- Groucho Marx


More information about the Rcpp-devel mailing list