CKTIS / Python
Set the profiling scope with cProfile.Profile.enable()
Start collecting data just before calling `run_profiled()`, stop in `finally`, and then inspect the results so setup and analysis stay outside the profile.
Version: Python 3.12
Syntax
import cProfile
profiler = cProfile.Profile()
profiler.enable()
try:
run_profiled()
finally:
profiler.disable()In Python 3.12, cProfile.Profile.enable is an instance method. Constructing a cProfile.Profile() does not start collection; calling profiler.enable() does. Calling profiler.disable() stops collection without discarding the data already collected. These two methods are not available on profile.Profile from the profile module.
Call enable() just before run_profiled() and put disable() in finally. This stops collection even if the profiled call raises an exception; finally does not itself catch that exception. Do setup before enabling the profiler and read the results with pstats.Stats(profiler) after disabling it.
The profile shows call counts and timings. Profiling adds overhead, so do not treat those timings as benchmark results.
Examples
import cProfile
import pstats
def outside_scope():
return 0
def run_profiled():
return sum(range(10))
profiler = cProfile.Profile()
outside_scope()
profiler.enable()
try:
run_profiled()
finally:
profiler.disable()
outside_scope()
functions = pstats.Stats(profiler).get_stats_profile().func_profiles
print('run_profiled:', 'run_profiled' in functions)
print('outside_scope:', 'outside_scope' in functions)Result
run_profiled: True outside_scope: False
Expect `True` for `run_profiled` and `False` for `outside_scope`. The example calls `outside_scope()` before enabling the profiler and again after disabling it. It checks for function names rather than comparing timings.
Related lessons
- Python · Lesson 15 · Advanced · Version: 5