pythonprofilingcprofile

Can I turn off profiling in a portion of python code when invoking cProfile as a script?


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?


Solution

  • It seems that the cProfile.Profile object created when run as a script is not accessible. The next best thing would be to instantiate cProfile.Profile in your program as close to the start as possible, and call disable() and enable() on that instance.

    This approach means you should no longer run cProfile as a script; that is, you should remove -m cProfile from the command line. Also you will have to add the code to print out the stats at the end of your program, because -m cProfile is no longer there to do it automatically for you.