Handy short cut for formatting elapsed time in floating point seconds
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Sun Apr 22 02:21:55 EDT 2007
On Sat, 21 Apr 2007 18:09:01 -0700, Paul McGuire 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)
I dispute that this is easiest. I think the timeit module is easier, and
more reliable.
You probably should be putting the lengthy operation in a function (you're
going to run the test more than once, right?), so you can do this:
import timeit
timeit.Timer("function()", "from __main__ import function").repeat()
or even:
s = """
# insert your code
# for the length operation
# here
"""
timeit.Timer(s, "").repeat()
Call help(timeit) for more details.
--
Steven.
More information about the Python-list
mailing list