[Tutor] Printing time without "if" statement

Steven D'Aprano steve at pearwood.info
Mon Mar 8 08:03:12 CET 2010


On Mon, 8 Mar 2010 03:38:49 pm Elisha Rosensweig wrote:
> Hi,
>
> I have an event-based simulator written in Python (of course). It
> takes a while to run, and I want to have messages printed every so
> often to the screen, indicating the simulation time that has passed.
> Currently, every event that occurs follows the following code
> snippet:
[...]
> This seems stupid to me - why should I have to check each round if
> the time has been passed? I was thinking that there might be a
> simpler way, using threading, but I have zero experience with
> threading, so need your help. The idea was to have a simple thread
> that waited X time (CPU cycles, say) and then read the "current_time"
> variable and printed it.
>
> Any simple (simpler?) solutions to this?

That's a brilliant idea. I think I will steal it for my own code :)

(Why didn't I think of it myself? Probably because I almost never use 
threads...)

Anyway, here's something that should help:


import time
import threading

class Clock(threading.Thread):
    def __init__(self, *args, **kwargs):
        super(Clock, self).__init__(*args, **kwargs)
        self.finished = False
    def start(self):
        print "Clock %s started at %s" % (self.getName(), time.ctime())
        super(Clock, self).start()
    def run(self):
        while 1:
            if self.finished:
                break
            print "Clock %s still alive at %s" % (
            self.getName(), time.ctime())
            time.sleep(2)
        print "Clock %s quit at %s" % (self.getName(), time.ctime())
    def quit(self):
        print "Clock %s asked to quit at %s" % (
        self.getName(), time.ctime())
        self.finished = True

def do_work():
    clock = Clock(name="clock-1")
    clock.start()
    # Start processing something hard.
    for i in xrange(8):
        print "Processing %d..." % i
        # Simulate real work with a sleep.
        time.sleep(0.75)
    clock.quit()



And in action:

>>> do_work()
Clock clock-1 started at Mon Mar  8 17:40:42 2010
Processing 0...
Clock clock-1 still alive at Mon Mar  8 17:40:43 2010
Processing 1...
Processing 2...
Clock clock-1 still alive at Mon Mar  8 17:40:45 2010
Processing 3...
Processing 4...
Processing 5...
Clock clock-1 still alive at Mon Mar  8 17:40:47 2010
Processing 6...
Processing 7...
Clock clock-1 still alive at Mon Mar  8 17:40:49 2010
Clock clock-1 asked to quit at Mon Mar  8 17:40:49 2010
>>> Clock clock-1 quit at Mon Mar  8 17:40:51 2010

>>>


There's a bit of a display artifact in the interactive interpreter, when 
the final quit message is printed: the interpreter doesn't notice it 
needs to redraw the prompt. But other than that, it should be fine.


-- 
Steven D'Aprano


More information about the Tutor mailing list