timer python generator

From Noah.org
Revision as of 20:35, 19 December 2013 by Root (talk | contribs) (Created page with 'Category: Engineering Category: Python This is the easiest way to run some code in a loop with a time-out. When the timeout is reached the loop will stop iterating. <pre…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search


This is the easiest way to run some code in a loop with a time-out. When the timeout is reached the loop will stop iterating.

#!/usr/bin/env python


def timer(duration):

    '''This is a generator that stops after the given duration (in seconds).
    Through each iteration it yields the time left. The duration may include
    fractional seconds such as "5.5". Example:

        for time_left in timer(10):
            print time_left
    '''

    import time
    end_time = time.time() + duration
    time_left = duration
    while time_left > 0:
        yield time_left
        time_left = end_time - time.time()


if __name__ == '__main__':
    import sys
    import time
    for time_left in timer(5):
        sys.stdout.write('\033[1G')  # CHA: cursor to column 1
        sys.stdout.write('%06.4f' % time_left)
        sys.stdout.flush()
    time.sleep(0.1)
    sys.stdout.write('\ndone\n')