Ways to improve this clock algorithm?

Bengt Richter bokr at oz.net
Sat Sep 20 11:28:09 CEST 2003


On Mon, 15 Sep 2003 23:45:55 +0200, Valentino Volonghi aka Dialtone <dialtone#NOSPAM#.despammed at aruba.it> wrote:

>jacobsmail at gmx.net (Jacob H) writes:
>
>> I am grateful for any suggestions and advice. :)
>
>import time
>class ExampleTimer(object):
>    def __init__(self):
>        print "This is my super clock"
>        self.run()
>
>    def run(self):
>        while 1:
>              self.update_time()
>              print "%s hrs %s min %s sec" % (self.hours, self.mins, self.secs)
>              time.sleep(1)
>
>    def update_time(self):
>        # I would use time.localtime() to update the time because doing this I am
>        # sure that it is always syncd with my pc time. I think this is the only
>        # improvement :). It also removes the need for all that math.
>        self.secs = time.localtime()[5]
>        self.mins = time.localtime()[4]
>        self.hours = time.localtime()[3]
Sooner or later a second will tick between the above statements and give inconsistent h,m,s.
Better to get the tuple, slice it and unpack it, e.g., (untested)

         self.hours, self.mins, self.secs = time.localtime()[3:6]

Also, time.sleep(1) will probably span an epsilon more than one second sometime, and
when that hits the second updates right you will get a 2-second hiccup in apparent time
output. As to when it will happen, it's only a matter of time ;-) (Unless you are running
on some platform that has some underlying synchronization with wall clock seconds going on).

One way to get around that might be to sync up with the seconds turnover, either with a
busy wait or with a minimal sleep interval, then sleep say .99 seconds and wait again in
a minimal sleep loop until the second-value changes (if it has not done so already due
to extraneous delays). You can fine tune various aspects of this (as an exercise ;-)

<rant>
This kind of ugliness results if there's no way to tell the OS a precise wall clock time
to ready your process/thread after a wait and/or if timers don't have a way of specifying
accurate intervals that work to the nearest tick and don't accumulate tick resolution errors.
Relatively simple to provide if you are coding the OS clock stuff, so why is application-level
timer expiration usually only relative to a precisely unpredictable "now" instead of a time
coordinate in some time coordinate system?
</rant>

>
>app = ExampleTimer()
>app.run()
>
>            
>
>-- 
>Valentino Volonghi, Regia SpA, Milan
>
>Linux User #310274, Debian Sid Proud User

Regards,
Bengt Richter




More information about the Python-list mailing list