[Python-Dev] release candidate rules and timeit API question

Skip Montanaro skip@pobox.com
Mon, 30 Jun 2003 21:23:43 -0500


    Tim> It's not so fine that this delicate code is duplicated, so I'd
    Tim> rather see an internal refactoring to use a common backoff-polling
    Tim> class.

I recently copied it to my own code as well.  I'd like to see it whacked
into something reusable.  This seems to work:

    import time
    class Timeout(Exception): pass

    def await_condition(predicate, timeout):
        delay = 0.0005
        endtime = time.time() + timeout
        while True:
            if predicate():
                return
            remaining = endtime - time.time()
            if remaining <= 0:          # time's up, predicate always failed
                raise Timeout
            delay = min(delay * 2, remaining, .05)
            time.sleep(delay)           # reduce CPU usage by using a sleep

Skip