[Python-ideas] time.Timer

Andrew Barnert abarnert at yahoo.com
Wed Feb 26 21:12:36 CET 2014


From: anatoly techtonik <techtonik at gmail.com>

Sent: Tuesday, February 25, 2014 9:24 PM


> UX improvement fix for the common case:
> 
> import time
> 
> class Timer(object):
>   def __init__(self, seconds):
>     self.seconds = seconds
>     self.restart()
> 
>   def restart(self):
>     self.end = time.time() + self.seconds
> 
>   @property
>   def expired(self):
>     return (time.time() > self.end)

time.time() is almost always the wrong thing to use for almost anything. It's a float, it doesn't guarantee precision better than 1 second, it can be slow (on the order of milliseconds), and it doesn't guarantee monotonicity. You probably wanted monotonic here, although without knowing your use case, it's possible you wanted monotonic_raw with a fallback to monotonic, or perf_counter.

Also, this kind of timer is only really appropriate for a frame-loop app (as in a traditional arcade game or digital audio app), where you're inherently only checking, say, once every 20ms when idle and less often when busy. But any such loop should be sharing a _single_ call to the clock for the entire loop instance, not reading the clock repeatedly. Plus, most such programs in Python are probably written in something like pygame, which already provides a nicely-integrated timer (and many of the rest probably should be…). In an event loop, or a program based on threads or coroutines, or anything other than a frame loop, this is the wrong thing to do.


More information about the Python-ideas mailing list