random.SystemRandom().randint() inefficient

Cecil Westerhof Cecil at decebal.nl
Wed Jul 27 05:17:05 EDT 2022


Dennis Lee Bieber <wlfraed at ix.netcom.com> writes:

> On Tue, 26 Jul 2022 23:47:59 +0200, Cecil Westerhof <Cecil at decebal.nl>
> declaimed the following:
>
>
>>The new code:
>>    from random  import SystemRandom
>>    system_random   = SystemRandom()
>>    index = system_random.randint(0, len(to_try) - 1)
>>
>>The first two statements are executed once.
>>The last statement I think about 75 * 10 ** 6.
>>
>>So it seems that my first idea of using randbelow was the correct one.
>>But if anyone could explain why SystemRandom is so much more
>>expensive, I would be interested to know it.
>>(Or am I still doing something wrong?)
>
> 	What happens with
>
> 		system_randint = SystemRandom().randint	#no parens
>
> 		index = system_randint(...)
>
> which may remove the method lookup from the repetition.

I had already switched to randrange. This went to 15 minutes from 21
minutes.
By removing the method lookup I could shave off another minute. So
certainly noteworthy. (Should have thought about it myself.)

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof


More information about the Python-list mailing list