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

Hendrik van Rooyen mail at microcorp.co.za
Mon Aug 28 04:43:41 EDT 2006


 "Claudio Grondi" <claudio.grondi at freenet.de> Wrote:

| Fredrik Lundh wrote:
| > 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>
| >
|
| This above is exactly what I am looking for, except it does not work in
| Microsoft Windows where the signal.alarm() function is not available.
|
| So now the only thing I would like to know is how to achieve the same
| functionality when running Python on a Microsoft Windows box.
|
| Claudio Grondi

It looks to me - but I could be wrong - that the time saved here is not because
of the condition test being replaced by the try-except, but because of the fact
that the call to gettime was eliminated - so you may get the most mileage by
using in line code in your loop that avoids calls to subroutines and simply let
it run and test for the end of the counter...

- Hendrik




More information about the Python-list mailing list