why are these exec times so different?
r.e.s.
r.s at XXmindspring.com
Wed Dec 17 15:49:35 EST 2003
To show that what I'm seeing isn't because of
local/global differences, here are dummy functions
that exhibit the same behavior. (And I've tried to
minimize os background activity, etc, when testing.)
The results are consistently repeatable: For the
given string s, f1(s) takes >10 times longer to run
than f2(s) -- f1(s) and f2(s) return the same value,
and contain essentially the same code, except that
f2 calls function g to do the common inner loop:
def f1(s):
""" do outer & inner loop """
D = {}
for i in xrange(len(s)):
for j in xrange(len(s)-i+1):
D[s[j:j+i]] = True
return len(D)
def f2(s):
""" same as f1, but call g to do inner loop """
count = 0
for i in xrange(len(s)):
count += g(s,i)
return count
def g(s,i):
""" the common inner loop """
D = {}
for j in xrange(len(s)-i+1):
D[s[j:j+i]] = True
return len(D)
def string01(n):
"""Return first n chars of a fixed pseudorandom string."""
random.seed(0)
return ''.join([ random.choice('01') for i in xrange(n) ])
import random, time
s = string01(1000)
t0 = time.clock()
test, count = 'f1:', f1(s)
#test, count = 'f2:', f2(s)
t1 = time.clock()
print test, count, t1-t0
More information about the Python-list
mailing list