How do I get time of a Python program's execution?
I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.
I've looked at the timeit
module, but it seems it's only for small snippets of code. I want to time the whole program.
Solution 1:
The simplest way in Python:
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
This assumes that your program takes at least a tenth of second to run.
Prints:
--- 0.764891862869 seconds ---
Solution 2:
I put this timing.py
module into my own site-packages
directory, and just insert import timing
at the top of my module:
import atexit
from time import clock
def secondsToStr(t):
return "%d:%02d:%02d.%03d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(t*1000,),1000,60,60])
line = "="*40
def log(s, elapsed=None):
print line
print secondsToStr(clock()), '-', s
if elapsed:
print "Elapsed time:", elapsed
print line
print
def endlog():
end = clock()
elapsed = end-start
log("End Program", secondsToStr(elapsed))
def now():
return secondsToStr(clock())
start = clock()
atexit.register(endlog)
log("Start Program")
I can also call timing.log
from within my program if there are significant stages within the program I want to show. But just including import timing
will print the start and end times, and overall elapsed time. (Forgive my obscure secondsToStr
function, it just formats a floating point number of seconds to hh:mm:ss.sss form.)
Note: A Python 3 version of the above code can be found here or here.