Python question
Steven W. Orr
steveo at syslang.net
Tue Jan 13 12:23:09 EST 2009
On Tuesday, Jan 13th 2009 at 11:39 -0000, quoth Shawn O'Shea:
=>time.time() returns the number of seconds since the epoch, so end-start
=>should be the number of seconds of execution. For example, given the
=>following program timetest.py:
=>import time
=>
=>start=time.time()
=>
=>time.sleep(5)
=>
=>end=time.time()
=>
=>print end-start
=>
=>The output should very close to 5 seconds (with some overhead for the
=>recording of start and end).
=>$ python timetest.py
=>5.00017285347
=>
=>If you are doing timing of code, you may also want to consider the timeit
=>module (part of the standard library):
=>http://docs.python.org/library/timeit.html
=>
=>-Shawn
=>
=>
=>On Tue, Jan 13, 2009 at 10:41 AM, Paul Lussier <p.lussier at comcast.net>
=>wrote:
=> "Thomas Charron" <twaffle at gmail.com> writes:
=>
=> > Example:
=> >
=> >>>> strftime("HH:MM:SS ", localtime())
=> > '14:17:15'
=>
=>Ah, I see. So, if I do this:
=>
=> >>> begin = time.time()
=> [... long wait here ... ]
=> >>> end = time.time()
=> >>> time.strftime("%H:%M:%S", time.localtime(end - begin))
=> '19:16:07'
=>
=>so, the MM:SS are correct, but the 19 for hours is incorrect. It
=>should be 00, because "long wait here" was 16:07.
=>
=> >>> end - begin
=> 967.31416082382202
=> >>> time.localtime(end - begin)
=> (1969, 12, 31, 19, 16, 7, 2, 365, 0)
=>
=>So far, it seems my best bet is to do the math on the difference
=>between end, begin myself; something like this:
=>
=> def ElapsedTime (time):
=> """Convert a float into HH:MM:SS string"""
=>
=> days = time / 60 / 60 / 24
=>
=> if days < 1:
=> days = 0
=>
=> mins = int(time / 60)
=> if mins > 60:
=> hours = int(mins / 60)
=> mins = int(time % 60)
=> else:
=> hours = 0
=>
=> secs = int(((time % 60) - int(mins)) * 60)
=>
=> days = (days < 10) and ("0%s" % days) or days
=> hours = (hours < 10) and ("0%s" % hours) or hours
=> mins = (mins < 10) and ("0%s" % mins ) or mins
=> secs = (secs < 10) and ("0%s" % secs ) or secs
=>
=> return "%s:%s:%s:%s" % (days, hours, mins, secs)
=>
=>I'm certainly appreciative of better ways to do this :)
=>
=>Thanks.
Guys, don't use time! Use the datetime interface I previously described.
That's what it was made for. :-)
#! /usr/bin/python
import datetime
import time
then = datetime.datetime.now()
print "then = ", then
time.sleep(5)
now = datetime.datetime.now()
print "now = ", now
print "Elapsed = ", now - then
--
steveo at syslang dot net TMMP1 http://frambors.syslang.net/
Do you have neighbors who are not frambors? Steven W. Orr
More information about the gnhlug-discuss
mailing list