[Rcpp-devel] Parallel random numbers using Rcpp and OpenMP

Mark Clements mark.clements at ki.se
Wed Apr 30 10:10:52 CEST 2014


My two cents worth:

For the microsimulation package, we needed uniform random number streams
and sub-streams at the C++ level, while supporting R's non-uniform
random number distributions[*]. For this, we used the C++ RngStreams
library and provided "double *user_unif_rand ()" for user-defined RNGs.
Essentially, this reproduces the "L'Ecuyer-CMRG" RNG provided by R, with
seed manipulation at the C++ level (cf. using .Random.seed and R's C
machinery). We also allow for the C++ seeds to be set to and from R.

See:
https://github.com/mclements/microsimulation/blob/master/src/microsimulation.cc
https://github.com/mclements/microsimulation/blob/master/src/microsimulation.h
(circa lines 290-355)
https://github.com/mclements/microsimulation/blob/master/R/rcpp_hello_world.R
(circa lines 6-36)

This is not implemented using OpenMP. For our purpose, where we are
doing 10^7 small simulations, we chunk the simulations at the R level
and use the parallel package to call the C++ code on each chunk. This
approaches scales well with more processors.

We have also looked at using the C++ RngStream library with
Boost.Random's and C++11's non-uniform random number distributions.
Again, this has not been implemented using OpenMP (todo?). For a simple
wrapper for Boost, see:
https://github.com/mclements/microsimulation/blob/master/src/rngstream-boost.hpp

with an example:
https://github.com/mclements/microsimulation/blob/master/src/rngstream-example.cpp

Two brief notes: first, we have put the RngStream library in the ssim
namespace for use with the microsimulation package. Other uses of the
Boost wrapper would probably want to change the namespace.

Second, the implementation for C++11 random number generators and
distributions required a small change to the RngStream library -
specifically, to output the random uniform as an unsigned long.
Interestingly, the resulting C++11 random numbers drop every second
value compared with R and Boost.Random.

For the C+++11 wrapper, see the code RngStream* and rngstream* in:
https://github.com/mclements/microsimulation/tree/master/test

Sincerely, Mark.

[*] The BH package was not available, C++11 compiler requirements were
not accepted on CRAN,  reimplementing non-uniform random number
distributions using UNURAN would have taken too long, and the R
non-uniform random number distributions are extensive and well tested.


More information about the Rcpp-devel mailing list