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

Dick Moores rdm at rcblue.com
Thu Oct 12 11:15:29 CEST 2006


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


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().

coin = choice(["heads", "tails"]).

instead, use

value = random()
if value >= .5:
     coin = "heads"
else:
     coin = "tails"

I tested these in order, using the template in random.py (a copy of 
it of course):

Evaluating timeitRandom-1.py
100 loops, best of 3: 4.24 msec per loop
SystemExit:
 >>>
Evaluating timeitRandom-2.py
10 loops, best of 3: 27.9 msec per loop
SystemExit:
 >>>
(Thanks, Kent)

Even with all the extra baggage attached to it, random() is 6.6 times 
faster than choice with no baggage!

Dick Moores



More information about the Tutor mailing list