What I usually do is use clock()
or time()
from the time
library. clock
measures interpreter time, while time
measures system time. Additional caveats can be found in the docs.
For example,
def fn():
st = time()
dostuff()
print 'fn took %.2f seconds' % (time() - st)
Or alternatively, you can use timeit
. I often use the time
approach due to how fast I can bang it out, but if you're timing an isolate-able piece of code, timeit
comes in handy.
From the timeit docs,
def test():
"Stupid test function"
L = []
for i in range(100):
L.append(i)
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
Then to convert to minutes, you can simply divide by 60. If you want the script runtime in an easily readable format, whether it's seconds or days, you can convert to a timedelta
and str
it:
runtime = time() - st
print 'runtime:', timedelta(seconds=runtime)
and that'll print out something of the form [D day[s], ][H]H:MM:SS[.UUUUUU]
. You can check out the timedelta docs.
And finally, if what you're actually after is profiling your code, Python makes available the profile library as well.