How to let a loop run for a while before checking for break condition?

Matimus mccredie at gmail.com
Wed Aug 30 01:40:08 EDT 2006


Claudio Grondi wrote:
> Sometimes it is known in advance, that the time spent in a loop will be
> in order of minutes or even hours, so it makes sense to optimize each
> element in the loop to make it run faster.
> One of instructions which can sure be optimized away is the check for
> the break condition, at least within the time where it is known that the
> loop will not reach it.
>
> Any idea how to write such a loop?
>
> e.g.
>
> counter = 2*64
>
> while counter(BUT DON'T CHECK IT THE FIRST ONE HOUR LONG):
>    ... do something ... # and decrease the counter
>
> Thanks for any hint, but in particular if related to timers on the
> Windows 2000/XP system I am mainly working with.
>
> What do you think about this idea? Does it make sense?
>
> Claudio Grondi

Would simple loop unrolling help? I've never experimented with loop
unrolling in python, but perhaps something like this would help. Also,
it sort of depends upon the condition. Do you know how many times 'do
something' will be performed before hand?

do_something = compile("print 'do_something'","loop.tmp","single")
loop_list = [do_something]*(loop_count)
for x in loop_list: exec(x)

Note that this offloads some work upfront but depending on what is
being done it might still be quicker. It will take up more memory, but
the list will only be full of references. I'm pretty sure that the for
loop, in this case, will not be doing a check each iteration since it
is operating on a list, but I'm not positive.




More information about the Python-list mailing list