Python Debugging Cheat Sheet/Profile code inside Python

Wrap a hot path in cProfile and print stats.

Section: Profiling and Memory

Profile code inside Python

python
python
import cProfile
import pstats

profiler = cProfile.Profile()
profiler.enable()
expensive_call()
profiler.disable()
pstats.Stats(profiler).sort_stats('tottime').print_stats(20)

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Profiling and Memory
Profile a script with cProfile
Collect function-level runtime statistics.
OpenIn sheetbashsame section
Sort cProfile output by total time
Surface slow functions first.
OpenIn sheetbashsame section
Track memory allocations with tracemalloc
Capture memory allocation snapshots.
OpenIn sheetpythonsame section
Inspect process memory and CPU with psutil
Check runtime resource usage from inside the process.
OpenIn sheetpythonsame section
Insert a built-in breakpoint
Pause execution and enter the configured debugger.
Print the current exception traceback
Dump the active exception traceback in an except block.