random.randint() slow, esp in Python 3

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Sep 22 20:14:16 CEST 2011


Chris Angelico wrote:

> The standard library function random.randint() seems to be quite slow
> compared to random.random(), and worse in Python 3 than Python 2
[...]
> But this still doesn't explain why randint() is so much slower. In
> theory, randint() should be doing basically the same thing that I've
> done here (multiply by the top value, truncate the decimal), only it's
> in C instead of Python - if anything, it should be faster than doing
> it manually, not slower.

What makes you think it's in C? I don't have Python 3.3a, but in 3.2 the
random module is mostly Python. There is an import of _random, which
presumably is in C, but it doesn't have a randint method:

>>> import _random
>>> _random.Random.randint
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object '_random.Random' has no attribute 'randint'


I'm not seeing any significant difference in speed between 2.6 and 3.2:

[steve at sylar ~]$ python2.6 -m timeit -s "from random import
randint" "randint(0, 1000000)"
100000 loops, best of 3: 4.29 usec per loop

[steve at sylar ~]$ python3.2 -m timeit -s "from random import
randint" "randint(0, 1000000)"
100000 loops, best of 3: 4.98 usec per loop


(The times are quite variable: the above are the best of three attempts.)



-- 
Steven




More information about the Python-list mailing list