From python-library-distribution
Profiles Python code with cProfile, PyInstrument, memray, and tracemalloc; benchmarks with pytest-benchmark; provides optimization strategies for bottlenecks and memory leaks.
How this skill is triggered — by the user, by Claude, or both
Slash command
/python-library-distribution:performanceThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
```bash
# PyInstrument (statistical, readable output)
python -m pyinstrument script.py
# cProfile (detailed, built-in)
python -m cProfile -s cumulative script.py
# Memory profiling
pip install memray
memray run script.py
memray flamegraph memray-*.bin
from pyinstrument import Profiler
profiler = Profiler()
profiler.start()
result = my_function()
profiler.stop()
print(profiler.output_text(unicode=True, color=True))
import tracemalloc
tracemalloc.start()
# ... code ...
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno')[:10]:
print(stat)
def test_encode_benchmark(benchmark):
result = benchmark(encode, 37.7749, -122.4194)
assert len(result) == 12
pytest tests/ --benchmark-only
pytest tests/ --benchmark-compare
# Use set for membership (O(1) vs O(n))
valid = set(items)
if item in valid: ...
# Use deque for queue operations
from collections import deque
queue = deque()
queue.popleft() # O(1) vs list.pop(0) O(n)
# Use generators for large data
def process(items):
for item in items:
yield transform(item)
# Cache expensive computations
from functools import lru_cache
@lru_cache(maxsize=1000)
def expensive(x):
return compute(x)
# String building
result = "".join(str(x) for x in items) # Not += in loop
| Operation | list | set | dict |
|---|---|---|---|
| Lookup | O(n) | O(1) | O(1) |
| Insert | O(1) | O(1) | O(1) |
| Delete | O(n) | O(1) | O(1) |
For detailed strategies, see:
Before Optimizing:
- [ ] Confirm there's a real problem
- [ ] Profile to find actual bottleneck
- [ ] Establish baseline measurements
Process:
- [ ] Algorithm improvements first
- [ ] Then data structures
- [ ] Then implementation details
- [ ] Measure after each change
After:
- [ ] Add benchmarks to prevent regression
- [ ] Verify correctness unchanged
- [ ] Document why optimization needed
This skill is based on the Performance section of the Guide to Developing High-Quality Python Libraries by Will McGinnis. See these posts for deeper coverage:
npx claudepluginhub wdm0006/python-skills --plugin python-library-completeProfiles and optimizes Python code using cProfile, memory profilers, and best practices. Use for debugging slow code, bottlenecks, CPU/memory issues, and app performance.
Profiles Python code for bottlenecks using cProfile and py-spy, applies optimization patterns like generators and NumPy, tunes memory with tracemalloc, and benchmarks with pytest-benchmark.
Profiles and optimizes Python code using cProfile, timeit, memory profilers, and best practices for bottlenecks, slow execution, high memory, and latency.