CKTIS / Python
Stop profiling with `cProfile.Profile.disable()`
Call `disable()` on the same `cProfile.Profile` instance to stop collecting data before analysis without discarding the statistics already gathered.
Version: Python 3.12
Syntax
profiler.disable()In Python 3.12, cProfile.Profile.disable is an instance method: call it as profiler.disable() with no arguments. It stops that profiler from collecting data without clearing what it has collected or printing a report. The enable() and disable() pair is available in cProfile, not in the profile module.
Prepare inputs before enabling the profiler. Call profiler.enable() immediately before run_profiled(), and put profiler.disable() in a finally block so collection stops even if run_profiled() raises an exception. The finally block does not catch that exception.
After collection stops, pass the same instance to pstats.Stats(profiler). This keeps the analysis itself outside the measured interval while retaining the data from the call to run_profiled().
Examples
import cProfile
import pstats
def outside_scope():
return sum(range(10))
def run_profiled():
return sum(range(1000))
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
The output shows which function names appear in the statistics, not how long the calls took. `run_profiled()` runs while profiling is active; both calls to `outside_scope()` run outside that interval.
Related lessons
- Python · Lesson 15 · Advanced · Version: 5