[Tutor] Why is random.choice so much slower than random.random()?

Kent Johnson kent37 at tds.net
Thu Oct 12 13:33:30 CEST 2006

```Dick Moores wrote:
> Why is random.choice so much slower than random.random()? In fact, by
> a factor of 12! And randint(). Some 25 times slower than random(). Why?
> (I know that random() is the basis for most of the other functions in
> the random module, and a look at random.py, though I don't complete
> understand it, gives me an idea what's going on with randint(), etc., still...)
>
> C:\>python -m timeit  -s"from random import choice" "for x in range(10000):
> " " choice([0, 1])"
> 10 loops, best of 3: 22.8 msec per loop
>
> C:\>python -m timeit  -s"from random import random" "for x in range(10000):
> " " random()"
> 1000 loops, best of 3: 1.84 msec per loop
>
> C:\>python -m timeit  -s"from random import uniform" "for x in range(10000)
> :" " uniform(0, 1)"
> 100 loops, best of 3: 12.2 msec per loop
>
> C:\>python -m timeit  -s"from random import randrange" "for x in range(1000
> 0):" " randrange(2)"
> 10 loops, best of 3: 25.3 msec per loop
>
> C:\>python -m timeit  -s"from random import randint" "for x in range(10000)
> :" " randint(0, 1)"
> 10 loops, best of 3: 45.9 msec per loop

Looking at the code and your numbers, my guess is that the time to make
a Python function call on your computer is about 2 microseconds (20 msec
/ 10000). (I mean the entire overhead - looking up the function and
actually calling it.)

random.randint() just calls random.randrange() after incrementing the
upper limit. So the difference in times between these two is one

randrange() does a little checking, then calls random(). The time
difference is a little more than 20 msec, probably due to the argument
checking.

> Anyway, if you are making a coin flipping program, with a great many
> flips and speed is important, it seems a good idea to avoid the
> otherwise obvious choice of choice().

And more generally, in a highly optimized loop, avoid function calls if
possible, they are relatively expensive in Python.

Kent

```