random.SystemRandom().randint() inefficient

Chris Angelico rosuav at gmail.com
Tue Jul 26 14:01:20 EDT 2022


On Wed, 27 Jul 2022 at 01:06, Cecil Westerhof via Python-list
<python-list at python.org> wrote:
>
> I need to get a random integer. At first I tried it with:
>     from secrets import randbelow
>     index = randbelow(len(to_try))
>
> This works perfectly, but it took some time. So I thought I try:
>     from random  import SystemRandom
>     index = SystemRandom().randint(0, len(to_try) - 1)
>
> A first indication is that the second version would take about two
> times as much time as the first. Is there a reason for this, or should
> this not be happening?
>

You're setting up a brand new SystemRandom instance just for a single
random number. For a fairer comparison, set up the instance, then
generate far more than just a single number, and see how that goes.

ChrisA


More information about the Python-list mailing list