Profiling Python

# At the top of the file in global scope
# next to the imports
import cProfile as profile
pr = profile.Profile()

# right before the function call to profile

# right after the function call to profile
# Now save results to file, with
# This should only be called once, if in doubt
# place right before your program exits.

alternatively for a whole script file:

python -m cProfile -o profile.pstat

Within a terminal do:

pip install pyprof2calltree
pyprof2calltree -i profile.pstat -o script.calltree
kcachegrind script.calltree