Raymond Moay - 9 months ago 31

Swift Question

Hi I'm new to programming here and I am curious if a larger limit number generator cause it to be slower when generating a random number? For example:

which one generates a random number faster?

`arc4random_uniform(1000000)`

or

`arc4random_uniform(10)`

Could it be the same speed?

Thanks!

Answer

Assuming your are talking about `arc4random_uniform`

instead of `arc4random`

since the later does not have an upper bound you can specify.

The answer is: **it might**!

Looking at the source and documentation:

Uniformity is achieved by generating new random numbers until the one returned is outside the range

`[0, 2**32 % upper_bound)`

. This guarantees the selected random number will be inside`[2**32 % upper_bound, 2**32)`

which maps back to [0, upper_bound) after reduction modulo upper_bound.

That means that the speed of the random number generation depends on the ratio between the upper limit of `arc4random`

and the afore mentioned modulo remainder.

In your example:

`2^32 % 10 = 4`

`2^32 % 1000000 = 967.296`

Creating a random number using `arc4random()`

one time yields for example `768.649`

which is smaller than the second value. That means it would have to create a second random number calling `arc4random()`

a second time for the later case - the first case is already done creating random numbers.

But that runtime difference is entirely up to change.

A second try might yield `1.316.166.055`

on the first try which causes both calls to take the same amount of time.

Since `arc4random`

is uniformly distributed the probability of the second one taking longer is somewhat close to `967.296 / 2^32`

which is `0.00022521615`

=> in `0.02%`

of the calls the second one takes longer than the first one.

In this calculation I ignored the fact that theoretically the `arc4random`

can even produce a number smaller than `4`

which would trigger even the first call to requery). But it should still give you an understanding of how improbable a difference will be.

If you want to get the probably "slowest" call you would have to perform `arc4random_uniform(2^31+1)`

which has a ~50% chance of failing on the first call to `arc4random`

.