Speed-up for loops

Terry Reedy tjreedy at udel.edu
Mon Sep 6 15:08:05 EDT 2010


On 9/6/2010 7:20 AM, Stefan Behnel wrote:
> BartC, 06.09.2010 12:38:

>> (3) Since the loop variable is never used, why not have a special loop
>> statement that repeats code so many times?

There sort-of is, just slightly more general.

> Because special cases are not special enough to break the rules. As
> others have stated before, you can use itertools to reduce that part of
> the looping overhead, if it really hurts your concrete code.

I ran the following test:
 >>> from itertools import repeat
 >>> n = 10**8
 >>> for dummy in repeat(None,n): pass # 7 sec

 >>> for dummy in range(n): pass # 11 sec

Times are for my older machine, subjectively counted. The difference is 
subjectively clear. Both functions count in C. I presume the difference 
is the cost of creating and deleting unneeded Python int objects. This 
difference is the reason the timeit module uses itertools.repeat for the 
inner loop that repeats the code to be timed.

-- 
Terry Jan Reedy




More information about the Python-list mailing list