New submission from Andrew Lin <onethreese...@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 <rep...@bugs.python.org>
<https://bugs.python.org/issue45976>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to