473,473 Members | 1,415 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Ways to improve this clock algorithm?

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
Jul 18 '05 #1
6 2902
ja********@gmx.net (Jacob H) writes:
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)


I think you mean

allseconds = int(now) - int(self.start)

Now you can say

hours = allseconds // 3600
minutes = (allseconds // 60) % 60
seconds = allseconds % 60

instead of counting up to allseconds. You could also use the divmod
function for a fancier way to do the same thing, but the above is
straightforward enough.
Jul 18 '05 #2
ja********@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]

app = ExampleTimer()
app.run()

--
Valentino Volonghi, Regia SpA, Milan

Linux User #310274, Debian Sid Proud User
Jul 18 '05 #3
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

Jul 18 '05 #4
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

Jul 18 '05 #5
Thanks to all for the replies. They did indeed improve my clock algorithm. ;)

Jake
Jul 18 '05 #6
On Mon, 15 Sep 2003 23:45:55 +0200, Valentino Volonghi aka Dialtone <di************************@aruba.it> wrote:
ja********@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
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: James Harriman | last post by:
Hi, I need to be able to measure a time interval in milliseconds on a windows machine. I have tried using time.clock() but it appears to measure time in seconds...Is there a way to measure time...
33
by: Pushkar Pradhan | last post by:
I'm using clock() to time parts of my code e.g. clk1 = clock(); /* code */ clk2 = clock(); /* calculate time in secs */ ...... clk1 = clock(); /* code */ clk2 = clock();
17
by: Sean Kenwrick | last post by:
I am writing a byte-code interpreter/emulator for a language that exclusively uses strings for variables (i.e all variables are pushed onto the stack as strings). Therefore for arithmetic...
41
by: Petr Jakes | last post by:
Hello, I am trying to study/understand OOP principles using Python. I have found following code http://tinyurl.com/a4zkn about FSM (finite state machine) on this list, which looks quite useful for...
54
by: CoreyWhite | last post by:
The following experiment is a demonstration of TIME TRAVEL. When writing this program, and testing it out I found that sometimes the program would engage itself in time travel but other times it...
7
by: dphizler | last post by:
This is the basic concept of my code: #include <iostream.h> #include <math.h> #include <stdlib.h> int main() { double Gtotal, L, size, distance, theRandom; double Gi; int xi, xf, yi, yf,...
12
by: cenktarhancenk | last post by:
is there a way to display a ticking clock in a web page using javascript? but not in a textbox, rather as text that i can change the style, font etc. cenk tarhan
75
by: At_sea_with_C | last post by:
Hello all, I have written an ascending sort routine for floats. This seems to do the job, but for elements over 10,000, it gets awfully slow. A lot of useless comparisions with previously sorted...
2
by: GaryDean | last post by:
This question is about alternate ways to hook into a web service. If we just add web reference in VS 2003 we got a wsdl, reference.cs, and reference.map. In vs2005 we get a wsdl and a discomap. ...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.