Raymond Hettinger <raymond.hettin...@gmail.com> added the comment:

Donovan, if the speed of the power of two case is important to you, I recommend 
using getrandbits() instead.  It is ten times faster.

  $ python3.9 -m timeit -r 11 -s 'from random import randrange, getrandbits' 
'randrange(2**32)'
  1000000 loops, best of 11: 362 nsec per loop

  $ python3.9 -m timeit -r 11 -s 'from random import randrange, getrandbits' 
'getrandbits(32)'
  10000000 loops, best of 11: 32 nsec per loop

The two referenced articles aren't pertinent to this issue, the power of two 
case for randrange(). Both articles boil down to finding that a single task, 
arity zero, C coded method is significantly faster than a pure python method 
with error checking, a complex signature, support for arbitrarily large 
integers, and extra effort to assure an equal distribution.  It is unsurprising 
random() is faster than randrange().  Code that does less work is faster than 
code that does more work.

Mark is correct that the current code wasn't an accident and that we 
intensionally chose to keep reproducibility.

I appreciate your suggestion, but it essentially same one that was rejected in 
bpo-37000.  As Mark pointed out, nothing has changed since then (though some 
other changes have been added to 3.10 that improved the speed of rangerange() 
without affecting reproducibility).

Note, even if the PR had been accepted, you would still be much better off with 
getrandbits().

----------
resolution:  -> duplicate
stage: patch review -> resolved
status: open -> closed
superseder:  -> _randbelow_with_getrandbits function inefficient with powers of 
two

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue43040>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to