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

Claudio Grondi claudio.grondi at freenet.de
Sun Aug 27 09:52:27 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.
> 
> 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.

Going to C or assembly addresses the speed, but does not address the 
question asked, as the problem of checking a condition in a loop remains 
the same (even if at another speed level).

Here some more context to put more light into what I would like to know 
about:
   any program runs within an operating system and this system (and in 
particular Microsoft Windows) does many, many things beside running the 
program. The idea is to use the resources wasted in cycles of the CPU 
spent on processing the other things anyway for the program itself.
I have only a vague draft of what I would like to achieve so please 
don't get what I write here about how I imagine it should be done too 
seriously:
   I think, that the application can start with an unconditional loop 
and tell the operating system to stop this loop and provide a response 
when e.g. one hour is over. When that happens a pre-prepared conditional 
loop will start (which was waiting to be awoken) assuming the same 
environment (values of variables will be preserved, so it is clear where 
to continue) as the previous one.

As an intermediate quick and dirty solution for practical use there is 
the possibility to let the Python script run into an error or to break 
its run with Ctrl+C if it is apparent it is ready (e.g. the first 
approach has just saved me 20 CPU minutes of a four CPU hours needing 
script and the condition was checking only the value of an iteration 
counter so was not a very time consuming one).

Just thought that for sure someone had already the same/similar idea and 
might share here an elegant Pythonic solution addressing this issue.

Claudio Grondi



More information about the Python-list mailing list