Profiling Python

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

# right before the function call to profile
pr.enable()

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

alternatively for a whole script file:

python -m cProfile -o profile.pstat script.py

Within a terminal do:

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

Leave a Reply

Your email address will not be published.