random.randint() slow, esp in Python 3
rosuav at gmail.com
Sat Sep 24 14:33:50 CEST 2011
On Sat, Sep 24, 2011 at 4:55 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Chris Angelico wrote:
> If you want unbiased, random (or at least pseudo-random) integers chosen
> from an uniform distribution with proper error checking, you should use
> randint or randrange.
> "I only need random-ish ints, but I need 'em yesterday!!!"
All I want is some data to sort, so that I can verify that my
implementation is doing the same thing in every language that I write
it in. Doesn't have to be casino-level purity of randomness.
> You can't measure the speed of:
> [random.randint(0,sz*10-1) for i in range(sz)]
> and draw conclusions about randint alone.
Sure, but by comparing the two lines of code (one with randint and one
with random()), the other aspects can be cancelled out.
> For what (little) it's worth, it seems that Python 3.2 should be a bit
> faster than 2.6, at least if you consider the Pystone benchmark to mean
That's what I would normally expect, that the new version outperforms
the old - regardless of the program and the context. Exceptions need
justification (as in the case of int/long vs just int - Py2 often
outperforms Py3 when all the numbers fit inside machine int).
> You do know that Python's heap implementation is written in C? Don't be
> fooled by the heapq module being in Python.
I didn't know, but it doesn't surprise me. But my purpose wasn't to
sort the integers, it was to play with a particular hand-rolled
implementation of a heap sort in multiple languages and make sure it
was producing consistent results.
More information about the Python-list