performance of script to write very long lines of random chars

Chris Angelico rosuav at gmail.com
Wed Apr 10 23:14:37 EDT 2013


On Thu, Apr 11, 2013 at 12:40 PM, gry <georgeryoung at gmail.com> wrote:
> Appealing idea, but it's slower than the array solution: 5min 13
> secs.  vs 4min 30sec for the array:
>
> for l in range(rows):
>     for i in xrange(nchars):
>         stdout.write(random.choice(avail_chrs))
>     stdout.write('\n')
>
>
> os.urandom does look promising -- I have to have full control over the
> charset, but urandom is very fast at generating big random strings...
> stay tuned...

Without actually profiling it, my first guess would be that calling
random.choice() for every character is an optimization target. (NOTE:
Do profile it, if the urandom method isn't sufficient straight-off.)
You may want to consider, for instance, generating larger random
numbers and doing some kind of translation on them - which is
fundamentally what the urandom/b64encode method is doing.

ChrisA



More information about the Python-list mailing list