[Tutor] python timers

Alan Gauld alan.gauld at btinternet.com
Thu Apr 21 09:55:06 CEST 2011


"michael scott" <jigenbakuda at yahoo.com> wrote

> As I was messing around with it I found a way to measure time... but 
> I'm
> positive there is a more elegant way to deal with this than what 
> I've thrown
> together.
>
> def thing():
>    start = time.time()
>    while 1:
>        now = time.time()
>        if now == start + 10.0:
>            print "times up"

I'd probably add a sleep() in there just to avoid too many unnecesary
operations burning the CPU. But othewise its a valid approach.

> How are timers usually implemented?

It depends on what you are doing, there are lots of options and no
single answer. Sometimes something similar to your solution is
the best fit. A simple pause is usually done with a sleep().
Sometimes the timer will be done in a thread - so the app can
keep on working on other things.

If you are doing a GUI there will usually be a timer mechanism
built into the GUI. Networking often uses select() to implement
a timer type function.

It just depends what you are trying to do.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list