Random number generation with OpenMP

In this parallel simulation using OpenMP, a coin is thrown many times and the number of tails is counted. The probability should be exactly 1/2.

This code is a backbone implementation of a parallelized loop using a thread-safe (reentrant) random number generator (drand48_r), uniformly distributed over the [0,1) interval, with OpenMP.

This backbone code (random_omp.c) is well-documented with comments and instructions, and can be used to perform other parallel simulations that are implemented over a loop and use random numbers.

Demo

The execution time is used to define the performance, measured in Mega trials per second. In an 8 processor, 16 core computer, running 4 threads and 2 millon tosses, the performance on average is about 250 megatrials per second and takes about 8 milliseconds.

$ ./random_omp 4 2000000
using OpenMP with 4/16 threads
thread: 0 seed: 1706223504
thread: 1 seed: 2092013418
thread: 3 seed: 569057117
thread: 2 seed: 509177014

number of tosses: 2000000
number of tails: 1000164

probability: 0.500082

execution time: 0.00802503 s
performance: 249.22 Mtrials/sec

With 2 billion tosses, the performance is on average 400 megatrials per second, and takes about 5 seconds. The following plot, using 16 threads, shows the well-known behavior of performance with increasing problem size.

The next plot shows the performance as a function of number of threads for 2 billion tosses, in an 8 processor, 16 core computer.

The speedup for this problem is ∼6.6, which gives an efficieny of 0.82. The parallel fraction of the problem is therefore about 97%.

Compilation and execution

Compile the code with,

$ gcc -Wall -o random_omp random_omp.c -fopenmp

and execute with the command line,

$ ./random_omp num_threads num_tries

where num_threads is the number of threads and num_tries is the number of coin tosses. To suppress the output to stderr,

$ ./random_omp num_threads num_tries 2>/dev/null

Dependencies

This software has been developed and tested using the GNU GCC compiler with OpenMP support. To determine if your GCC compiler has OpenMP support, execute the following command,

$ echo | cpp -fopenmp -dM | grep -i open

If the response is non-empty, for example,

#define _OPENMP 201511

the compiler has built-in OpenMP support. The _OPENMP preprocessor macro defines the year and month of the implemented OpenMP version, in decimal value format yyyymm.

List of Files

Included in this software package are the following files:

  • random_omp.c (C code)
  • README (documentation)
  • terms.md (terms of use)
  • license.md (license)

Terms of Use and License

Before buying, please read our Terms of Use and License.