Another question

Michael Hudson mwh21 at cam.ac.uk
Tue Apr 18 02:38:17 CEST 2000


"Jeff Massung" <jmassung at magpiesystems.com> writes:

> Donald Beaudry wrote in message <200004172120.RAA11102 at zippy.init.com>...
> >and this one is better still (at least on my machine):
> >
> >  def do_it():
> >      from random import randint
> >      r = [0,] * 100000
> >      for i in xrange(100000):
> >         r[i] = randint(1,10)
> >  do_it()
> >
> 
> With the "from/import" being local, does the namespace go away after the
> function is done? How fast is importing (say I called do_it() 10000 times -
> then how efficient is your function?)

Pretty fast; two dictionary lookups (once in sys.modules, another in
random.__dict__), for strings that will have been interned.

For that last dreg of performance you might try:

import random
def do_it(randint=random.randint,xrange=xrange):
    r = [0,] * 100000
    for i in xrange(100000):
       r[i] = randint(1,10)
do_it()

But really, this is getting silly; if performance is this much of an
obsession you aren't going to have that much fun with Python.

Cheers,
M.

-- 
59. In English every word can be verbed. Would that it were so in 
    our programming languages.
     -- Alan Perlis, http://www.cs.yale.edu/~perlis-alan/quotes.html



More information about the Python-list mailing list