pythonic way to optimize access to imported value?

Jeff Epler jepler at unpythonic.net
Sat Nov 16 09:29:44 EST 2002


> In article <aqrig4$d2h$0 at 216.39.172.122>, Bengt Richter <bokr at oz.net> wrote:
> >Here's a toy example. I just want to make a function that efficiently
> >uses (here just returns) something from a module. 
> 
On Sat, Nov 16, 2002 at 02:18:41AM -0500, Aahz wrote:
> Can you explain a bit more clearly what the purpose of this?

Speed, I assume.

f0 0.945003986359	# empty loop
f1 2.456807971		# math.pi
f2 1.20684301853	# (local) pi

LOAD_FAST is bound to be faster than LOAD_GLOBAL + LOAD_ATTR.

Jeff


import math, time

R = range(1000000)
def f0():
    for i in R: pass

def f1():
    for i in R: math.pi

def f2(pi=math.pi):
    for i in R: pi

for f in (f0, f1, f2):
    t0 = time.time()
    f()
    t1 = time.time()
    print f.__name__, t1-t0




More information about the Python-list mailing list