Skip to content

Instantly share code, notes, and snippets.

@krivonogov
Forked from axelborja/profiling_python.py
Created October 31, 2016 11:23
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krivonogov/dfe5f164c2aa2796fa212ef4258c2ff1 to your computer and use it in GitHub Desktop.
Save krivonogov/dfe5f164c2aa2796fa212ef4258c2ff1 to your computer and use it in GitHub Desktop.
Profile your python code using CProfile or Yappi and KCachegrind / QCachegrind
################
# CPROFILE #
#############################################################################
# 1 - Profile myfunc() from ipython
import cProfile
filename = 'filename.prof'
cProfile.run('myfunc()', filename)
# 2 - Convert your file to a usable kcachegrind file in your shell
# ?> sudo pip install pyprof2calltree
# ?> pyprof2calltree -i filename.prof -o callgrind.filename.prof
# 3 - Open callgrind.filename.prof in kcachegrind
#############################################################################
########################
# EMBEDDED CPROFILE #
#############################################################################
# 1 - Profile few lines in your code.
import cProfile
filename = 'filename.prof'
pr = cProfile.Profile()
pr.enable()
# ... lines to profile ...
pr.disable()
pr.dump_stats(filename)
# 2 - Convert your file to a usable kcachegrind file in your shell
# ?> sudo pip install pyprof2calltree
# ?> pyprof2calltree -i filename.prof -o callgrind.filename.prof
# 3 - Open callgrind.filename.prof in kcachegrind
#############################################################################
#############
# YAPPI #
#############################################################################
# 1 - Profile myfunc() from ipython or from your code
import yappi
filename = 'callgrind.filename.prof'
yappi.set_clock_type('cpu')
yappi.start(builtins=True)
myfunc()
stats = yappi.get_func_stats()
stats.save(filename, type='callgrind')
# 2 - Open callgrind.filename.prof in kcachegrind
#############################################################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment