mercredi 18 mai 2016

Is it good Python practice to reuse SystemRandom?

For example, a block of Python code to generate 1 million random strings off the alphabet 'abcdef'.

Compare

from random import SystemRandom

for _ in range(1000000):
    ''.join(SystemRandom().choice('abcdef') for __ in range(5))

with

from random import SystemRandom

r = SystemRandom()
for _ in range(1000000):
    ''.join(r.choice('abcdef') for __ in range(5))

I timed it on IPython. The 1st block took 50s while the 2nd block took 30s. I didn't measure the memory usage.

In Java, there is SecureRandom where the pattern is clear that it should be created once and reused. Coming from Java to Python, it is not clear to me whether I should create a single SystemRandom instance and reuse it. The 1st block is easier to read and the performance does not seem too bad.

In general, does Python programming pay more attention to readability than performance?




Aucun commentaire:

Enregistrer un commentaire