On 5/5/06, Luke Paireepinart <rabidpoobear@xxxxxxxxx> wrote:but the line for l in range(0,length):
would be faster if you said l = 0 while l < length: l+=1
I believe, because then python doesn't have to generate an array of integers that's (length) long, which is what the range() function does in the for loop version.
while doing an explicit counter doesn't hog a bunch of memory like range does, it really isn't any faster.... the builtin xrange on the other hand, which uses a generator to return the list values is probably the best way to do a simple counter-type for loop
on my machine, range is a memory hog, but is faster than an explicit counter until a loop of about 1 million and range gets much worse from there, while xrange was always less than half the speed of the explicit counter (makes sense, when it's less than half the code)
for the curious, attached is a some python code to see the difference between range, xrange and an explicit counter on your own machine(s) ------------------------------------------------------------------------
import timeit
def iter_counter(length): l = 0 while l < length: num = l l+=1 return num
def iter_range(length): for l in range(0,length): num = l return num
def iter_xrange(length): for l in xrange(0,length): num = l return num
def print_function_timings(func_name, count): statement = "%s(%d)" % (func_name, count) print " timed:",func_name timer = timeit.Timer(statement, "from __main__ import %s"%func_name) results = timer.repeat(3, 1) print " average:", reduce(lambda a,b: a+b, results)/len(results) print " min:", min(results) return min(results) def print_function_comparison(loop_size): print "Comparing",loop_size,"iterations" range_time = print_function_timings("iter_range", loop_size) counter_time = print_function_timings("iter_counter", loop_size) xrange_time = print_function_timings("iter_xrange", loop_size) print "counter vs. range: %.1f%% less time"%(100*(range_time - counter_time)/range_time) print "xrange vs. counter: %.1f%% less time"%(100*(counter_time - xrange_time)/counter_time) print ""
print_function_comparison(10000) print_function_comparison(1000000) print_function_comparison(100000000)