# Ways to improve this clock algorithm?

Jeff Epler jepler at unpythonic.net
Mon Sep 15 23:49:21 CEST 2003

```Well, this doesn't run on my system.  First, I had to change this line:
>             now = time.clock()
-             allseconds = int(now) = int(self.start)
+             allseconds = int(now) - int(self.start)
>             seconds = 0
[In all the excerpts, "-" is a line changed/removed from your version,
and "+" is a line changed/added in my version]

Then, I had to insert an 'import':
+ import time
+
> class ExampleTimer:
>     def __init__(self):

Then, this program kept printing "0 hrs 0 min 0 sec", because clock()
returns CPU time (not wall time) on Unix computers.  time.time() returns
seconds on all systems Python supports, according to the online
documentation. ("import time; help(time.time)")

>     def __init__(self):
-         self.start = time.clock()
+         self.start = time.time()

>         while 1:
-             now = time.clock()
+             now = time.time()

Finally, I'm not sure what your 'for n in range ...' code is intended to
do.  You can convert the number of seconds into the
hours/minutes/seconds more easily:
# (Replacing the whole 'for' loop and the three asignments above it)
# Take whole minutes and leave the seconds corresponding to the
# fraction of minutes in seconds
minutes = allseconds / 60
seconds = allseconds % 60

# Take whole hours and leave the minutes corresponding to the
# fraction of the hour in minutes
hours = minutes / 60
minutes = minutes % 60
You could do this with the built-in function divmod(), as well:
# (Replacing the whole 'for' loop and the three asignments above it)
minutes, seconds = divmod(allseconds, 60)
hours, minutes = divmod(minutes, 60)

You could test starting at different times by changing init:
-     def __init__(self):
-         self.start = time.clock()
+     def __init__(self, offset=0):
+         self.start = time.clock() - offset

Now, you can easily see whether the "rollover" to 1 hour works right:
- app = ExampleTimer()
+ app = ExampleTimer(60*60 - 1)
> app.run()

Jeff

```