If we wish to know how long it takes for a portion of code to run, an obvious answer is to time it:

For example:

from time import time
start = time()
# do_something()
end = time()
print('It took {end - start} seconds!')

When the program grows, doing this is impractical, but python provides us, by default, with the cProfile module to get information about the running time of our program’s functions.

Using cProfile is to import it into our program and pass the python code we wish to analyse.

import cProfile
cProfile.run("do_something()")

This method is more valuable than time the function, as the output includes more information, including sub-functions called in the function do_something()

An even better approach is to run our whole program. For that, we call the python interpreter as:

python -m cProfile myprogram.py

We can arrange the output sorted by time:

python -m cProfile -s time myprogram.py

Last, if we need to investigate our program’s performance further, we can store the profiling results in a file and use another utility to analyse the data. For example:

python -m cProfile -o myprogram.prof myprogram.py

Now we can use install SnakeViz via pip, and start SnakevViz:

snakeviz myprogram.prof

The user interface is quite user-friendly and easy to research your data in the provided interface via your web browser.