Handy short cut for formatting elapsed time in floating point seconds

John Machin sjmachin at lexicon.net
Sun Apr 22 03:36:39 CEST 2007


On Apr 22, 11:09 am, Paul McGuire <p... at austin.rr.com> wrote:
> I am doing some simple timing of some elements of Python scripts, and
> the simplest is to just call time.time() before and after key elements
> of the script:
>
> t1 = time.time()
>
> # do lengthy operation
>
> t2 = time.time()
> print "That took %f seconds" % (t2-t1)

Why would you do %f and not %.3f ?

>
> Unfortunately, this gives very ugly timing output, as just a floating
> point number of seconds.  After several iterations of writing a
> formatter (strftime is not straightforward to use - it omits
> milliseconds for one thing), I came up with this:
>
> def secondsToStr(t):
>     rediv = lambda ll,b : list(divmod(ll[0],b)) + ll[1:]
>     return "%d:%02d:%02d.%03d" % tuple(reduce(rediv,[[t*1000,],
> 1000,60,60]))
>
> Now I can write:
>
> print "That took", secondsToStr(t2-t1),"seconds"
>
> and get nicely-formatted 0:00:12.345 style output.

and it it runs for (say) 83+ seconds you will get
"That took 0:01:23.456 seconds" which is ludicrous.
And if you want to calculate a percentage speed-up later you will have
to convert back to seconds.
>
> (I also posted this to the Python Cookbook.)
>
> -- Paul

IMHO if your job is short,
print "That took %.3f seconds" % (t2 - t1)
is adequate, and your leading 0:00: is useless.
If it runs for minutes or hours, then minutes or hours to (say) 4
significant digits is more than adequate, and printing milliseconds is
useless.




More information about the Python-list mailing list