Faster random integer generation with batching

We often generate random integers. Quite often these numbers must be within an interval: e.g., an integer between 0 and 100. One application is a random shuffle. A standard algorithm for a fair random shuffle is the Knuth algorithm:

void shuffle(mytype *storage, uint64_t size) {
  for (uint64_t i = size; i > 1; i--) {
    uint64_t nextpos = random(i); // random value in [0,i)
    std::swap(storage[i - 1], storage[nextpos]);
  }
}

It is how the C++ function std::shuffle is implemented, as well as any similar standard shuffle function. Notice how it requires you to generate random integers in even changing intervals.

Meanwhile, most modern (pseudo) random integer functions generate 64-bit integers. Indeed, our processors are 64-bit bits running on 64-bit operating systems. Thus we must convert these 64-bit integers to whatever else we need, whether they are integers in an interval or a floating-point number.

You might be tempted to using a modulo operation (random() % 100). While it generates a random number between 0 and 100, it also uses a statistical bias. Further, if the value 100 is not know at compile-time (i.e., it is a changing value), it may compile down to a division instruction, which is relatively expensive. There is a better approach that requires no division most of the time and is used by many programming language standard libraries:

uint64_t random_bounded(uint64_t range) {
  __uint128_t random64bit, multiresult;
  uint64_t leftover;
  uint64_t threshold;
  random64bit = rng(); // 64-bit random integer
  multiresult = random64bit * range;
  leftover = (uint64_t)multiresult;
  if (leftover < range) {
    threshold = -range % range;
    while (leftover < threshold) {
      random64bit = rng();
      multiresult = random64bit * range;
      leftover = (uint64_t)multiresult;
    }
  }
  return (uint64_t)(multiresult >> 64); // [0, range)
}

If you are using GCC for C++ programming under Linux (glibc++), you are already using this trick. If you are a macOS user with LLVM and libc++, you are probably  relying on a slower approach.

Is that the best we can do?

Think about the scenario where you must generate an integer in the interval [0,100) and then an integer in the interval [0,99). Could you generate both such integers form a single 64-bit random integer?

Indeed, you can, and you can avoid the division instructions once more. The code is somewhat similar although a bit more complicated. In theory, the algorithm needs to compute the product of the two ranges, but we only compute it if needed.

// product_bound can be any integer >= range1*range2
// it may be updated to become range1*range2
std::pair<uint64_t, uint64_t> 
 random_bounded_2(uint64_t range1, uint64_t range2,
                   uint64_t &product_bound) {
  __uint128_t random64bit, multiresult;
  uint64_t leftover;
  uint64_t threshold;
  random64bit = rng(); // 64-bit random integer
  multiresult = random64bit * range1;
  leftover = (uint64_t)multiresult;
  uint64_t result1 = (uint64_t)(multiresult >> 64); // [0, range1)
  multiresult = leftover * range2;
  leftover = (uint64_t)multiresult;
  uint64_t result2 = (uint64_t)(multiresult >> 64); // [0, range2)
  if (leftover < product_bound) {
    product_bound = range2 * range1;
    if (leftover < product_bound) {
      threshold = -product_bound % product_bound;
      while (leftover < threshold) {
        random64bit = rng();
        multiresult = random64bit * range1;
        leftover = (uint64_t)multiresult;
        result1 = (uint64_t)(multiresult >> 64); // [0, range1)
        multiresult = leftover * range2;
        leftover = (uint64_t)multiresult;
        result2 = (uint64_t)(multiresult >> 64); // [0, range2)
      }
    }
  }
  return std::make_pair(result1, result2);
}

It has one limitation: the product of the two ranges must fit in a 64-bit word. Still, it be used to shuffle arrays, as long as they don’t exceed too much 1 billion elements:

void shuffle_2(mytype *storage, uint64_t size) {
  uint64_t i = size;
  for (; i > 1 << 30; i--) {
    uint64_t index = random_bounded(i, g); 
    // index is in [0, i-1]
    std::swap(storage[i - 1], storage[index]);
  }

  // Batches of 2 for sizes up to 2^30 elements
  uint64_t product_bound = i * (i - 1);
  for (; i > 1; i -= 2) {
    auto [index1, index2] = random_bounded_2(i, i - 1, 
         product_bound, g);
    // index1 is in [0, i-1]
    // index2 is in [0, i-2]
    std::swap(storage[i - 1], storage[index1]);
    std::swap(storage[i - 2], storage[index2]);
  }
}

Of course, you can extend this trick to 3, 4, 5, 6… elements, but it gets more complicated.

Is it fast? Let us test with a standard random number generator is C++ (std::mt19937_64). I wrote a C++ benchmark.

Let us first consider an M2 macBook with Apple/LLVM 15:

number of elements standard shuffle (ns/element) batched shuffle (ns/element)
10000 12.4 2.4
1000000 12.0 2.5

So we are four to five times faster than the standard library. Not bad.

What about Linux with an Intel processor and GCC 12? Then our batched approach is about 30% faster than the standard library. Notice how the Linux/GCC base results are much better: that’s because it is already using a well optimized routine. Still: 30% is not a bad gain.

number of elements standard shuffle (ns/element) batched shuffle (ns/element)
10000 2.2 1.7
1000000 3.5 2.7

Of course, the batched generation of random numbers applies to other important operations. Shuffling is just the most obvious one.

This is joint work with Nevin Brackett-Rozinsky.

References:

 

Appendix: Code

#ifndef TEMPLATE_SHUFFLE_H
#define TEMPLATE_SHUFFLE_H

#include <cstdint>
/**
 * Nevin Brackett-Rozinsky, Daniel Lemire, Batched Ranged Random Integer Generation, Software: Practice and Experience (to appear)
 * Daniel Lemire, Fast Random Integer Generation in an Interval, ACM Transactions on Modeling and Computer Simulation, Volume 29 Issue 1, February 2019
 */
namespace batched_random {

template <class URBG> uint64_t random_bounded(uint64_t range, URBG &&rng) {
  __uint128_t random64bit, multiresult;
  uint64_t leftover;
  uint64_t threshold;
  random64bit = rng();
  multiresult = random64bit * range;
  leftover = (uint64_t)multiresult;
  if (leftover < range) {
    threshold = -range % range;
    while (leftover < threshold) {
      random64bit = rng();
      multiresult = random64bit * range;
      leftover = (uint64_t)multiresult;
    }
  }
  return (uint64_t)(multiresult >> 64); // [0, range)
}


// product_bound can be any integer >= range1*range2
// it may be updated to become range1*range2
template <class URBG>
std::pair<uint64_t, uint64_t> random_bounded_2(uint64_t range1, uint64_t range2,
                                               uint64_t &product_bound,
                                               URBG &&rng) {
  __uint128_t random64bit, multiresult;
  uint64_t leftover;
  uint64_t threshold;
  random64bit = rng();
  multiresult = random64bit * range1;
  leftover = (uint64_t)multiresult;
  uint64_t result1 = (uint64_t)(multiresult >> 64); // [0, range1)
  multiresult = leftover * range2;
  leftover = (uint64_t)multiresult;
  uint64_t result2 = (uint64_t)(multiresult >> 64); // [0, range2)
  if (leftover < product_bound) {
    product_bound = range2 * range1;
    if (leftover < product_bound) {
      threshold = -product_bound % product_bound;
      while (leftover < threshold) {
        random64bit = rng();
        multiresult = random64bit * range1;
        leftover = (uint64_t)multiresult;
        result1 = (uint64_t)(multiresult >> 64); // [0, range1)
        multiresult = leftover * range2;
        leftover = (uint64_t)multiresult;
        result2 = (uint64_t)(multiresult >> 64); // [0, range2)
      }
    }
  }
  return std::make_pair(result1, result2);
}

// This is a template function that shuffles the elements in the range [first,
// last).
//
// It is similar to std::shuffle, but it uses a different algorithm.
template <class RandomIt, class URBG>
extern void shuffle_2(RandomIt first, RandomIt last, URBG &&g) {
  uint64_t i = std::distance(first, last);
  for (; i > 1 << 30; i--) {
    uint64_t index = random_bounded(i, g); // index is in [0, i-1]
    std::iter_swap(first + i - 1, first + index);
  }

  // Batches of 2 for sizes up to 2^30 elements
  uint64_t product_bound = i * (i - 1);
  for (; i > 1; i -= 2) {
    auto [index1, index2] = random_bounded_2(i, i - 1, product_bound, g);
    // index1 is in [0, i-1]
    // index2 is in [0, i-2]
    std::iter_swap(first + i - 1, first + index1);
    std::iter_swap(first + i - 2, first + index2);
  }
}

} // namespace batched_random

#endif // TEMPLATE_SHUFFLE_H

Daniel Lemire, "Faster random integer generation with batching," in Daniel Lemire's blog, August 17, 2024, https://lemire.me/blog/2024/08/17/faster-random-integer-generation-with-batching/.
[BibTeX]

Published by

Daniel Lemire

A computer science professor at the University of Quebec (TELUQ).

16 thoughts on “Faster random integer generation with batching”

  1. Naïve questions: Is there any benefit to working in (say) 128 bits instead of 64? That is, how much of the speed up is merely from not throwing away a huge amount of entropy when n is small? Is there an incremental design that folds in new entropy word-by-word, thereby avoiding the trade offs when n nears the max rand value (increased rejection risk), more closely approximating optimality without the tyranny of fixed bit widths?

    1. 1. Generating random 64-bit values can be relatively cheap (a few instructions) or significantly more expensive… In the manuscript (https://arxiv.org/abs/2408.06213) we covert both cases. Evidently, if the generation of the random bits is more expensive, there is greater relative benefits at not throwing away random bits… but the benefits remain even for cheap random bits.

      2. You can go from batches of two to batches of six (see manuscript) and get benefits, but these benefits will depend on how well your compiler does its jobs. LLVM is very good. Other compilers might not do such a great job. I suspect that batches of two is the more obvious and robust case (although the maximal benefits are less).

      3. Most generators produce 64 bits, because that’s the size of our registers. (Note that older generators work produce 32-bit for the obvious reason that it matches what the processors were capable at a the time.) To produce wider outputs, I expect that you will probably want to use SIMD instructions. If you used SIMD instructions to produce 128-bit or 256-bit words, then it becomes more of an open problem. Please see my blog post at https://lemire.me/blog/2018/07/23/are-vectorized-random-number-generators-actually-useful/ where I examined the problem briefly. A deeper investigation into SIMD algorithms might be warranted.

    2. I explored a couple of incremental methods here: https://github.com/KWillets/range_generator .

      The first one addresses rejection risk — a fractional part with more bits than the range is doable and decreases rejection exponentially.

      The extra bits can also be consumed conditionally, only if the first are ambiguous. It adapts from small n to big n where the need-more-bits case starts to dominate.

      The second one is more focused on the incremental aspect — you can consume as little as one random bit at a time, but you pay the cycles for calculating and checking if it can terminate there.

  2. This is only obliquely related to the topic, but I thought I’d mention the technique I use to generate strong random *double* values.

    I read 7 bytes from /dev/urandom, then fold across them starting with a double value 0 and each time adding the next byte and then dividing by 256.

    Here it is in Fexl. I could very easily code it in C for a built-in but I haven’t cared yet:

    https://github.com/chkoreff/Fexl/blob/master/src/lib/list.fxl#L406

    Some key test vectors are as follows, with the byte values expressed in decimal:

    [blockquote]
    # Test vectors:
    # [0 0 0 0 0 0 0] => 0
    # [255 255 255 255 255 255 63] => 0.25
    # [255 255 255 255 255 255 127] => 0.5
    # [255 255 255 255 255 255 191] => 0.75
    # [255 255 255 255 255 255 255] => 1
    [/blockquote]

    That gives you a double r in the range 0 <= r <= 1, so if you want a double s in the range 0 <= s <= X, you just use s = r*X.

    The only problem is that often you want 0 <= s < X. There's an astronomically low probability of s == X, so if you want to exclude that you have to reject r == 1. Rather than loop, I just check for r == 1 and set it to 0 in the unlikely case it happens. That gives an extremely tiny bias toward 0.

    To generate a random integer n in the range 0 <= n < X, I can use n = trunc(s). This probably won't be as fast as your pure integer algorithm, since I drag in the floating point baggage, but it gets the job done.

  3. Have you compared this approach with MergeShuffle [1]? One of the main features of their algorithm is that it parallelizes well, but even the sequential algorithm seems to be about twice as fast as Fisher-Yates, which is approximately the speedup that you are getting too.

    1. https://arxiv.org/abs/1508.03167

    1. seems to be about twice as fast as Fisher-Yates

      Do you know of major systems, like a C++ standard library, that has adopted the sequential version of this algorithm? If so, we will eagerly investigate.

      1. I couldn’t find a C++ implementation and I couldn’t even get the code that comes with the MergeShuffle article to run on my machine, so I think it’s reasonable to ignore it.

    2. My understanding is that MergeShuffle is most useful in the domain of very large data sets, because it can easily be parallelized across multiple processors. Thus I expect that a MergeShuffle implementation could incorporate our batched algorithm as part of its base case to shuffle contiguous chunks of data which fit in cache on a single processor.

      Specifically, step 3 of algorithm 2 in the MergeShuffle paper that you linked says to shuffle each block independently using Fisher-Yates. That step could be sped up by using our batched approach. Similarly, steps 15–19 of algorithm 3 in that paper amount to using Fisher-Yates to finish merging two blocks after one has been exhausted, and this too could be accelerated with batching. So it seems to me that MergeShuffle and our method are complementary, each operating efficiently at a different scale, and having the potential to mesh together seamlessly.

      1. You’re right, your approach is somewhat orthogonal to MergeShuffle. What both approaches have in common is that they try to reduce the number of wasted random bits. In any case, the idea of extracting multiple random numbers from a single RNG output is more broadly applicable than just to shuffling, so it’s a useful idea to publish regardless.

        By the way, did you know that libstdc++ also extracts two indices from a single RNG output in its std::shuffle() implementation, just with division/modulo instead of Lemire’s mostly-divisionless algorithm? [1-3] This might be worth mentioning as prior art in the paper.

        Interestingly enough, this algorithm is *slower* than textbook Fisher-Yates when I tried benchmarking it, especially for smaller arrays (by around 15%). Yet in your benchmarks, the “naive shuffle_2” method (which I understand to be approximately the same) is nearly as fast as “shuffle_2”, and a lot faster than “shuffle”. Do you have an explanation for that?

        1. https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libstdc%2B%2B-v3/include/bits/stl_algo.h;h=778a37ac46f4af245dafef06499be1e052112402;hb=refs/heads/master#l3649
        2. https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=38e34671fa2bb8a686cd2e2c770937b8c9be8f1e
        3. https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=9d8ff2f63be0ec81f2d90da84ec8cd8e800dbfd4

        1. By the way, did you know that libstdc++ also extracts two indices from a single RNG output in its std::shuffle() implementation, just with division/modulo instead of Lemire’s mostly-divisionless algorithm?

          I was unaware. It appears to have happened with this commit in 2016
          https://gcc.gnu.org/git/?p=gcc.git;a=commit;f=libstdc%2B%2B-v3/include/bits/stl_algo.h;h=9d8ff2f63be0ec81f2d90da84ec8cd8e800dbfd4

          Note that the divisionless is still there and it happened later. See https://gcc.gnu.org/git/?p=gcc.git;a=commit;f=libstdc%2B%2B-v3/include/bits/uniform_int_dist.h;h=822c1d21a3c710831af65a6e3bc83f558fb39044

          But yeah, it is kind of a shame that this was not optimized.

          This might be worth mentioning as prior art in the paper.

          Note that our paper does not include C++ benchmarks. The C++ benchmarks were prepared specifically for this blog post and are not part of the paper.

          Still, it would have been good to know about this prior art.

          Unfortunately, journal articles do not get updates. We definitively should have mentioned it, but we did not know about it.

          However, if I am ever involved in related work in the future, I will definitively mention it.

          Interestingly enough, this algorithm is *slower* than textbook Fisher-Yates when I tried benchmarking it, especially for smaller arrays (by around 15%). Yet in your benchmarks, the “naive shuffle_2” method (which I understand to be approximately the same) is nearly as fast as “shuffle_2”, and a lot faster than “shuffle”. Do you have an explanation for that?

          Our paper does not use C++ nor does it use GCC.

          This being said, if you look again at our paper, the “naive shuffle2” can be slower than a standard Fisher-Yates if the random number generator is 64-bit and sufficiently fast, especially on Intel processors.

  4. You’re right, your approach is somewhat orthogonal to MergeShuffle. What both approaches have in common is that they try to reduce the number of wasted random bits. In any case, the idea of extracting multiple random numbers from a single RNG output is more broadly applicable than just to shuffling, so it’s a useful idea to publish regardless.

    By the way, did you know that libstdc++ also extracts two indices from a single RNG output in its std::shuffle() implementation, just with division/modulo instead of Lemire’s mostly-divisionless algorithm? [1-3] This might be worth mentioning as prior art in the paper.

    Interestingly enough, this algorithm is *slower* than textbook Fisher-Yates when I tried benchmarking it, especially for smaller arrays (by around 15%). Yet in your benchmarks, the “naive shuffle_2” method (which I understand to be approximately the same) is nearly as fast as “shuffle_2”, and a lot faster than “shuffle”. Do you have an explanation for that?

    1. https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libstdc%2B%2B-v3/include/bits/stl_algo.h;h=778a37ac46f4af245dafef06499be1e052112402;hb=refs/heads/master#l3649
    2. https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=38e34671fa2bb8a686cd2e2c770937b8c9be8f1e
    3. https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=9d8ff2f63be0ec81f2d90da84ec8cd8e800dbfd4

  5. as a noob, i don’t understand this part of the codebase
    threshold = -range % range;
    isn’t modulo of same value regardless of sign always zero?

  6. It’s possible to generate outputs one at a time, at the cost of one extra widening multiplication and rejection test per output value. And with a gain of more outputs per underlying RNG call.

    Basically, it’s
    uint64_t random_bounded(uint64_t range, uint64_t (*rng)(void)) {
    static uint64_t leftover, modulus = -1ull;
    __uint128_t product;

    product = (_uint128_t)modulus * range;
    if (product <= TOOBIG) {
    modulus = (uint64_t)product;
    leftover = (uint64_t)(product = (__uint128_t)range * leftover);
    if (leftover >= modulus || leftover >= -modulus % modulus)
    return (uint64_t)(product >> 64);
    }

    modulus = range;
    leftover = (uint64_t)(product = (__uint128_t)range * rng());
    leftover = (uint64_t)product;
    if (leftover < range) {
    uint64_t threshold = -range % range;
    while (leftover < threshold)
    leftover = (uint64_t)(product = (__uint128_t)range * rng());
    }
    return (uint64_t)(product >> 64);
    }

    (static used for simplicity; replace with the thread-safe construct of your choice.)

    The main tuning thing is the value of TOOBIG. Obviously, -1ull is the largest possible value. But if the modulus gets close to that value, then a division will be triggered every time before we fall back to fresh rng() output, which makes things not “nearly divisionless”.

    Let p = TOOBIG*0x1p-64. Assuming leftover is uniformly distributed, the fast path will return a result with probability (1-p) with no divide, and p/2 after a divide. (Making the much less justifiable assumption that -modulus % modulus is uniformly distributed in [0, modulus), so its mean value is modulus/2.) The remaining p/2 of the time, we waste a divide and fall through to the slow path anyway.

    So the cost delta of the fast path is p*DIVIDE_COST – (1-p/2) * RNG_COST. (Where both of those constants include some overhead, such as the widening multiply.)

    The cost is negative (it’s a net win) when p < 1 / (DIVIDE_COST/RNG_COST + 0.5). If DIVIDE_COST is less than half of RNG_COST, then p should be 1 (TOOBIG = -1ull). If the costs are equal, then p = 2/3. If DIVIDE_COST is 3*RNG_COST, p = 2/7.

    Also, there’s a way to tweak the structure of the fallback path to have only a single rng() call, which makes inlining easier:

    uint64_t threshold = range;
    do {
    leftover = (uint64_t)(product = (__uint128_t)range * rng());
    } while (leftover < threshold && (threshold != range || leftover < (threshold = -range % range)));

    return (uint64_t)(product >> 64);

    This relies on modern branch predictors to notice that leftover < threshold is almost always false, as is threshold != range (if reached). So the messy conditional doesn’t have to slow the processor down. You might want to add unlikely annotations to the source as well.

Leave a Reply

Your email address will not be published.

You can also subscribe by email to this blog (non-commercial, no ads, weekly email).

How to post code (C, C++, Java, Python, etc.):

Wrap your code in backticks, like this:

`int main() {
    return 0;
}`