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

Fredrik Lundh fredrik at pythonware.com
Sun Aug 27 09:34:09 EDT 2006


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):

def func2(timeout):

     gettime = time.time
     t_limit = gettime() + timeout

     count = 0
     while gettime() < t_limit:
         count += 1
     for i in range(10):
         count += 1
     print count

</F>




More information about the Python-list mailing list