Dirk Eddelbuettel — written Aug 3, 2013 — source
Markov Chain Monte Carlo (MCMC) is a popular simulation method. As it is somewhat demanding, it is also frequently used to benchmark different implementations or algorithms.
This post simply refreshes the implementation using Rcpp attributes.
First we look at the R version, and its byte-compiled variant.
Creating a version in C++ is very straightforward thanks to Rcpp and
Rcpp Attributes. It transfers the integer arguments
n (number of
thn (number of extra thinning simulations),
initializes the R random number generator for us (eg no need to manual
RNGScope object), and returns the result matrix
Also, since the initial posts were written, we made the (scalar) RNGs
of the R API available directly via the
R namespace. This is both
little nice to read than the poor-man’s pseudo-namespace in C via the
Rf_ prefix, and actually provides proper C++ namespace.
With the functions in place, we can re-run the benchmark.
test replications elapsed relative 3 RcppGibbs(n, thn) 10 1.161 1.00 2 RCgibbs(n, thn) 10 45.763 39.42 1 Rgibbs(n, thn) 10 57.995 49.95
As we have seen before, the C++ version is about 50 times faster, and around 40 times faster than the byte-compiled version.
A related article here on the Rcpp Gallery looks into timing different RNG implementation as this study revealed that the generator for Gamma-distributed random number in R is not particularly fast.Tweet