Ways to improve this clock algorithm?

Andy Jewell andy at wild-flower.co.uk
Mon Sep 15 17:57:27 EDT 2003


On Monday 15 Sep 2003 10:02 pm, Jacob H wrote:
> Hello all,
>
> I'm close to being a novice programmer and I never was good at math.
> So I'm curious to know ways in which this following code can be made
> more efficient, more elegant. The code just calculates and displays
> elapsed wall clock seconds since initialization.
>
> class ExampleTimer:
>     def __init__(self):
>         self.start = time.clock()
>
>     def run(self):
>         while 1:
>             now = time.clock()
>             allseconds = int(now) = int(self.start)
>             seconds = 0
>             minutes = 0
>             hours = 0
>             for n in range(1, (allseconds + 1)):
>                 seconds += 1
>                 if n % 60 == 0:
>                     minutes += 1
>                     seconds = 0
>                 if n % 3600 == 0:
>                     hours += 1
>                     minutes = 0
>             print "%s hrs %s min %s sec" % (hours, minutes, seconds)
>             time.sleep(1)
>
> app = ExampleTimer()
> app.run()
>
> I am grateful for any suggestions and advice. :)
>
> Jake

Jake,

Maybe this'll help:
>>> import time
>>> start=time.time()
>>> # waste some time...
>>> now=time.time()-start
>>> now
266.24996101856232
>>> secs=int(now % 60)
>>> secs
26
>>> mins=int((now-secs) /60)
>>> mins
4
>>> hrs=int((now-secs-mins) /(60*60))
>>> hrs
0
>>> 

-andyj





More information about the Python-list mailing list