[New-bugs-announce] [issue45976] Random._randbelow() loses time by caching an attribute lookup

Andrew Lin report at bugs.python.org
Fri Dec 3 21:20:56 EST 2021


New submission from Andrew Lin <onethreeseven at gmail.com>:

This PR obtains a performance improvement in the random module by removing a cached attribute lookup in Random._randbelow_with_getrandbits() that costs time on average.  In the best cases (on my machine) I get 10% improvement for randrange(), 7% for shuffle(), and 11% for sample(), with no change in the worst cases.

To elaborate...  If n is slightly less than a power of 2, _randbelow_with_getrandbits(n) almost always makes just one call to getrandbits(), so caching the attribute lookup never pays for itself.  Even in the worst case, when n is exactly a power of 2, the expected number of calls to getrandbits() is still only 2, and on my machine caching just breaks even.  (A friend ran it on ARM and got even more favorable results.)

I included a similar change to _randbelow_without_getrandbits() on similar grounds, although I didn't benchmark it.

(Brand new here; let me know if I've left anything out!)

----------
components: Library (Lib)
messages: 407625
nosy: onethreeseven
priority: normal
severity: normal
status: open
title: Random._randbelow() loses time by caching an attribute lookup
type: performance
versions: Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45976>
_______________________________________


More information about the New-bugs-announce mailing list