Python Profiling and Troubleshooting Cheat Sheet

Profile Python programs, inspect memory and imports, and diagnose slow or stuck processes.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Startup and Import Troubleshooting
Show import statements as they happen
python -v app.py

# Print detailed import resolution activity.

Print site-package configuration
python -m site

# Inspect interpreter paths and site initialization.

## Performance Hotspots
Save cProfile output to a file
python -m cProfile -o profile.stats app.py

# Store profile stats for later analysis.

Inspect saved profile stats
import pstats

stats = pstats.Stats('profile.stats')
stats.sort_stats('cumtime').print_stats(30)

# Read and sort a saved profile run.

## Memory Growth
Show garbage collector stats
import gc

print(gc.get_count())
print(gc.get_stats())

# Inspect GC activity when memory grows unexpectedly.

Force a garbage collection cycle
import gc

unreachable = gc.collect()
print(unreachable)

# Useful for experiments while diagnosing leaks.

Recommended next

No recommendations yet.