Profiling Python code
Copy pasta for when I need to profile python code again
cProfile
Built in so no
pip install
needed.
import cProfile
pr = cProfile.Profile()
pr.enable()
# *** Code Here *** #
pr.disable()
pr.print_stats()
View stats with snakeviz
Snakeviz is a nice browser based graphical viewer for cProfile
pr.dump_stats("filename.prof")
pip install snakeviz
snakeviz filename.prof
Here there are more ways to analyze the cProfille
dumps.
pprofile
Pprofile gives out a nice output that has a line by line profiling info for the code.
# Example from the PyPi page https://pypi.org/project/pprofile/
import pprofile
def someHotSpotCallable():
# Deterministic profiler
prof = pprofile.Profile()
with prof():
# *** Code to profile *** #
prof.print_stats()
def someOtherHotSpotCallable():
# Statistic profiler
prof = pprofile.StatisticalProfile()
with prof(
period=0.001, # Sample every 1ms
single=True, # Only sample current thread
):
# *** Code to profile *** #
prof.print_stats()
You can dump stats to a nice readable text file as well.
prof.dump_stats("filename.txt")