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.
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.
Ipython "timeit" any script:
If you want to measure time in microseconds, then you can use the following version, based completely on the answers of Paul McGuire and Nicojo - it's a Python3 code. I've also added some colour to it:
log() => function that prints out the timing info.
txt ==> first argument to log, and it's string to mark timing.
atexit ==> python module to register functions that you can call when program exits.
To use metakermit's updated answer for python 2.7 you will require the monotonic package.
The code would then be as follows:
The following snippet prints elapsed time in a nice human readable
<HH:MM:SS>
format.Even better for Linux:
/usr/bin/time
Normally, just
time
is a simpler shell builtin that shadows the more capable/usr/bin/time
.I put this
timing.py
module into my ownsite-packages
directory, and just insertimport timing
at the top of my module:I can also call
timing.log
from within my program if there are significant stages within the program I want to show. But just includingimport timing
will print the start and end times, and overall elapsed time. (Forgive my obscuresecondsToStr
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.