Say I need N cryptographically-secure pseudorandom integers within the range [0, K). The most obvious way of achieving this would be N calls to arc4random_uniform(3)
, and this is exactly what I’m doing.
However, the profiler tells me that numerous calls to arc4random_uniform(3)
are taking 2/3 of the whole execution time, and I really need to make my code faster. This is why I‘m planning to generate some random bytes in advance (probably with arc4random_buf(3)
) and subsequently extract from it bit by bit.
For K = 2, I can simply mask the desired bit out, but when K is not a power of 2, things are getting hairy. Surely I can use a bunch of %=
and /=
, but then I would have modulo bias. Another problem is when N grows too large, I can no longer interpret the whole buffer as an integer and perform arithmetic operations on it.
In case it’s relevant, K would be less than 20, whereas N can be really large, like millions.