Advertisement
Guest User

Performance of uniform_int_distribution

a guest
Apr 2nd, 2015
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <random>
  2. #include <cinttypes>
  3. #include <iostream>
  4.  
  5. // This is C99's suggested RNG.  It's a very basic LCG.  It's fast.
  6. typedef std::linear_congruential_engine<uint32_t, 1103515245u, 12345u, 0u>
  7.         c99_engine;
  8.  
  9. volatile uint32_t forced_store;
  10.  
  11. // An alternative to uniform_int_distribution, as found in pcg_extras;
  12. // assumes that the range of the RNG is strictly larger than the upper bound.
  13.  
  14. template <typename RngType>
  15. auto bounded_rand(RngType& rng, typename RngType::result_type upper_bound)
  16.         -> typename RngType::result_type
  17. {
  18.     typedef typename RngType::result_type rtype;
  19.     rtype threshold = (RngType::max() - RngType::min() + rtype(1) - upper_bound)
  20.                     % upper_bound;
  21.     for (;;) {
  22.         rtype r = rng() - RngType::min();
  23.         if (r >= threshold)
  24.             return r % upper_bound;
  25.     }
  26. }
  27.  
  28. int main()
  29. {
  30.     c99_engine engine{0};
  31.      
  32.     std::uniform_int_distribution<> dist(0, 5);    
  33.     typedef decltype(dist.param()) params;
  34.  
  35.     for (uint32_t i = 2; i < 1000000000; ++i) {
  36.         // forced_store = engine();
  37.         // forced_store = dist(engine);
  38.         // forced_store = bounded_rand(engine, 6);
  39.         forced_store = dist(engine, params(0,i-1));
  40.         // forced_store = bounded_rand(engine, i);
  41.     }
  42.    
  43.     return 0;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement