Fastest way to count your iterations?

Jeff Epler jepler at unpythonic.net
Mon Jul 28 16:31:06 EDT 2003


You could use generator functions as one way to implement a spinner.

    from __future__ import generators
    import sys, time

    # I think this may be called "cycle" in 2.3's itertools
    def spinner_next(chars):
        while 1:
            for c in chars: yield c

    def spinner(interval=100, chars="/-\\||", pos=0):
        ci = spinner_next(chars)
        while 1:
            # for interval iterations, don't advance spinner
            for i in range(interval): yield None
            # OK, now advance spinner
            # and print it in a low-tech fashion
            sys.stdout.write(ci.next()+"\n"); sys.stdout.flush()

    def calculate():
        j = 0
        s = spinner(10)
        for i in range(1000):
            time.sleep(.01)
            j = j + i
            s.next() # advance spinner 1 iteration
        print j
    calculate()

Jeff





More information about the Python-list mailing list