Use Claude to Profile and Optimise a Slow Python Script
When a Python script is slow, the bottleneck is rarely where you expect. Instead of guessing, run a profiler and paste the output to Claude — it reads the numbers and tells you exactly what to fix.
# Generate a cProfile report sorted by cumulative time
python -m cProfile -s cumulative slow_script.py 2>&1 | head -40
Paste the output directly into Claude:
Here's the cProfile output for my data processing script. Identify the bottlenecks and suggest concrete optimisations. Prioritise changes with the highest impact first.
Claude reads the cumtime column, pinpoints expensive calls, and suggests targeted fixes — swapping a nested loop for a set lookup, replacing a DataFrame iterrows with vectorised operations, or batching database calls that fire in a hot loop.
# Before: O(n²) — list scan inside a loop
results = [item for item in data if item in expensive_list]
# After: O(n) — set lookup
lookup = set(expensive_list)
results = [item for item in data if item in lookup]
For memory-heavy scripts, swap cProfile for memory_profiler:
pip install memory-profiler
python -m memory_profiler slow_script.py
Paste that output and ask Claude to suggest generators, chunked file processing, or numpy arrays instead of Python lists to cut peak memory usage.
You can also ask Claude to add @profile decorators to the specific functions it identifies as hotspots, so you get line-level granularity on the next run.
Profile first, optimise second — let Claude read the numbers so you don't have to.
Log in to leave a comment.
Set up Claude Code as an automated reviewer in your CI pipeline — on every pull request, it reads the diff, checks for bugs, security issues, missing tests, and convention violations, then posts its findings as a PR comment. Your human reviewers get a head start because the obvious issues are already flagged before they look.
Before deploying, tell Claude to read your project — migrations, environment variables, queue workers, scheduled tasks, caching, third-party integrations — and generate a deployment checklist that's specific to your app. Not a generic "did you run migrations?" list, but one that knows YOUR infrastructure and catches the things YOUR deploy can break.
Instead of writing a README from memory or copying a template, tell Claude to read your project and generate one that's actually accurate — real setup instructions from your config, real architecture from your directory structure, real API examples from your routes, and real prerequisites from your dependency files.