Another question

Bill Scherer scherbi at bam.com
Mon Apr 17 17:54:07 CEST 2000


I just did a little test and found this to be substantially fatser than the
other three:

import random
randint = random.randint

r = []

for i in xrange(1,10000):
    r.append(randint(1,10))

for i in r: print i
#


note that I dropped the second arg to xrange down by 2 orders.  I couldn't
wait for a million to scroll by ;-) , but the technique should scale.

I tested each algorithm 3 times and average the times.  My first attempt
was actually the slowest of the first three at 3.59.  Jeff's first (the
first listed) came in at 3.43, and his second at 3.48.  The above came in
at 2.49, ~44% faster than my first, and ~37% faster than Jeff's 3.43.

Bill Scherer wrote:

> Jeff -
>
> The main reason (AFAIK) you don't want to do 'from <mod> import *' is to
> avoid namespace clashing.
> A better way is this:
>
> #untested
> import random
> randint = random.randint
>
> for i in xrange(1,1000000):
>     print randint(1,10)
>
> #
>
> This method allows you to control exactly which names you import into
> your local namespace form the module.  The above should also be a little
> faster due to the use of xrange.  Se the docs for why.
>
> -Bill
>
> Jeff Massung wrote:
>
> > Okay, another quick question. If it is quicker to do:
> >
> > import random
> > from random import randint
> > for i in range(1,1000000):
> >     print randint(1,10)
> >
> > than this:
> >
> > import random
> > for i in range(1,1000000):
> >     print random.randint(1,10)
> >
> > Why would I not do "from <module> import *" with every module I load?
> >
> > Jeff
> >
> > --
> > http://www.python.org/mailman/listinfo/python-list
>
> --
> http://www.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list