How to let a loop run for a while before checking for break condition?
Diez B. Roggisch
deets at nospam.web.de
Sun Aug 27 10:36:46 EDT 2006
Fredrik Lundh schrieb:
> Diez B. Roggisch wrote:
>
>> 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.
>
> or use a timer interrupt to interrupt the loop:
>
> import signal, time
>
> def func1(timeout):
>
> def callback(signum, frame):
> raise EOFError # could use a custom exception instead
> signal.signal(signal.SIGALRM, callback)
> signal.alarm(timeout)
>
> count = 0
> try:
> while 1:
> count += 1
> except EOFError:
> for i in range(10):
> count += 1
> print count
>
> for an utterly trivial task like the one in that example, the alarm
> version runs about five times faster than a polling version, on my test
> machine (ymmv):
No doubt that changing the flag asynchronously is a gain by delegating
the timing code to the OS. Yet the while loop still has a condition - so
you could as well set a flag in the signal handler an do it like this:
def func3(timeout):
global flag
flag = True
def callback(signum, frame):
global flag
flag = False
signal.signal(signal.SIGALRM, callback)
signal.alarm(timeout)
count = 0
while flag or True:
count += 1
for i in range(10):
count += 1
print count
This is on my machine about 1.5 times slower than func1, but much more
readable especially wrt the OPs request of a condition being evaluated
after a certain timeout, as you don't repeat any code.
And apart from that, the overall gain of performance diminishes the very
moment anything non-trivial occurs in the loops body anyway.
Diez
More information about the Python-list
mailing list