I want to profile my code, but exclude startup.
Python docs describe how to run cProfile as a script:
python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py)
They also describe how to turn profiling on and off using the python API:
import cProfile
pr = cProfile.Profile()
pr.enable()
# ... do something ...
pr.disable()
Will it be effective to run pr.enable() and pr.disable() if I am running cProfile as a module?
Is there an implied "enable" when starting my code that I could disable, or is the cProfile object used by the script method not accessible to me?
It seems that the
cProfile.Profileobject created when run as a script is not accessible. The next best thing would be to instantiatecProfile.Profilein your program as close to the start as possible, and calldisable()andenable()on that instance.This approach means you should no longer run cProfile as a script; that is, you should remove
-m cProfilefrom the command line. Also you will have to add the code to print out the stats at the end of your program, because-m cProfileis no longer there to do it automatically for you.