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.
It runs
your_module.main()
function one time and print the elapsed time usingtime.time()
function as a timer.To emulate
/usr/bin/time
in Python see Python subprocess with /usr/bin/time: how to capture timing info but ignore all other output?.To measure CPU time (e.g., don't include time during
time.sleep()
) for each function, you could useprofile
module (cProfile
on Python 2):You could pass
-p
totimeit
command above if you want to use the same timer asprofile
module uses.See How can you profile a Python script?
Timeit is a class in python used to calculate the execution time of small blocks of code.
Default_timer is a method in this class which is used to measure the wall clock timing not CPU execution time. Thus other process execution might interfere with this. Thus it is useful for small blocks of code.
A sample of the code is as follows:
The simplest way in Python:
This assumes that your program takes at least a tenth of second to run.
Prints:
You can use the python profiler cProfile to measure CPU time and additionally how much time is spent inside each function and how many times each function is called. This is very useful if you want to improve performance of your script without knowing where to start. This answer to another SO question is pretty good. It's always good to have a look in the docs too.
Here's an example how to profile a script using cProfile from a command line:
time.clock()
time.perf_counter()
time.process_time()
This is Paul McGuire's answer that works for me. Just in case someone was having trouble running that one.
call
timing.main()
from your program after importing the file.