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

Tal Einat tal.no.no.spam at gmail.com
Sun Aug 27 08:55:04 EDT 2006


Diez B. Roggisch wrote:
> > The idea is to speed up a loop by using a timer interrupt interfering
> > with the loop, so that only after the timer interrupt would occur, the
> > loop will start to check its break condition in each iteration.
> > No checking of any kind in the loop should happen up to that time to
> > minimize the number of operations in each iteration within the loop
> > itself (i.e. the loop more or less won't know, that there is a timer on
> > its way to change the loops behavior at a later time).
>
> A while loop has a condition. period. The only thing to change that is
> to introduce a uncoditioned loop, and use self-modifying code to make it
> a while-loop after that timer interrupt of yours.
>
True. Still, if checking the condition is slowing down the loop,
perhaps it could be optimized somewhat by having a timeout set a
boolean flag, thus having the loop check a simpler condition, which may
be faster.

You can have a separate thread time.sleep() for as long as you want,
and then set the flag which the loop's condition checks. This way you
don't call time.time() on every iteration.

Another approach could be partial loop nesting/unrolling, if the
condition doesn't necessarily have to be checked on every iteration.
Just have an outer loop checking the condition, and an inner loop
(possibly unrolled) doing whatever it is your loop does, several times
(2-1000000, optimize for your needs). This just lets you check the
condition less often.

> But of course that whole thing is a moot point - if shaving mu-secs on
> that level is needed for your application, use C or assembly instead.
>
I agree, though those aren't the only alternatives - you could also try
going "half-way" with Pyrex.

- Tal Einat
reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))],
       [[chr(154-ord(c)) for c in '.&-&,l.Z95193+179-']]*18)[3]




More information about the Python-list mailing list