Python Performance Optimization

Python Performance Optimization

Teaches an AI agent to profile and speed up Python code with cProfile and memory profilers, tackling CPU, memory, I/O and algorithmic bottlenecks.

Skill files3 files

references/

SKILL.md101 lines
1
---
2
name: python-performance-optimization
3
description: Profile and optimize Python code using cProfile, memory profilers, and performance best practices. Use when debugging slow Python code, optimizing bottlenecks, or improving application performance.
4
---
5
6
# Python Performance Optimization
7
8
Comprehensive guide to profiling, analyzing, and optimizing Python code for better performance, including CPU profiling, memory optimization, and implementation best practices.
9
10
## When to Use This Skill
11
12
- Identifying performance bottlenecks in Python applications
13
- Reducing application latency and response times
14
- Optimizing CPU-intensive operations
15
- Reducing memory consumption and memory leaks
16
- Improving database query performance
17
- Optimizing I/O operations
18
- Speeding up data processing pipelines
19
- Implementing high-performance algorithms
20
- Profiling production applications
21
22
## Core Concepts
23
24
### 1. Profiling Types
25
26
- **CPU Profiling**: Identify time-consuming functions
27
- **Memory Profiling**: Track memory allocation and leaks
28
- **Line Profiling**: Profile at line-by-line granularity
29
- **Call Graph**: Visualize function call relationships
30
31
### 2. Performance Metrics
32
33
- **Execution Time**: How long operations take
34
- **Memory Usage**: Peak and average memory consumption
35
- **CPU Utilization**: Processor usage patterns
36
- **I/O Wait**: Time spent on I/O operations
37
38
### 3. Optimization Strategies
39
40
- **Algorithmic**: Better algorithms and data structures
41
- **Implementation**: More efficient code patterns
42
- **Parallelization**: Multi-threading/processing
43
- **Caching**: Avoid redundant computation
44
- **Native Extensions**: C/Rust for critical paths
45
46
## Quick Start
47
48
### Basic Timing
49
50
```python
51
import time
52
53
def measure_time():
54
"""Simple timing measurement."""
55
start = time.time()
56
57
# Your code here
58
result = sum(range(1000000))
59
60
elapsed = time.time() - start
61
print(f"Execution time: {elapsed:.4f} seconds")
62
return result
63
64
# Better: use timeit for accurate measurements
65
import timeit
66
67
execution_time = timeit.timeit(
68
"sum(range(1000000))",
69
number=100
70
)
71
print(f"Average time: {execution_time/100:.6f} seconds")
72
```
73
74
## Detailed patterns and worked examples
75
76
Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.
77
78
## Best Practices
79
80
1. **Profile before optimizing** - Measure to find real bottlenecks
81
2. **Focus on hot paths** - Optimize code that runs most frequently
82
3. **Use appropriate data structures** - Dict for lookups, set for membership
83
4. **Avoid premature optimization** - Clarity first, then optimize
84
5. **Use built-in functions** - They're implemented in C
85
6. **Cache expensive computations** - Use lru_cache
86
7. **Batch I/O operations** - Reduce system calls
87
8. **Use generators** for large datasets
88
9. **Consider NumPy** for numerical operations
89
10. **Profile production code** - Use py-spy for live systems
90
91
## Common Pitfalls
92
93
- Optimizing without profiling
94
- Using global variables unnecessarily
95
- Not using appropriate data structures
96
- Creating unnecessary copies of data
97
- Not using connection pooling for databases
98
- Ignoring algorithmic complexity
99
- Over-optimizing rare code paths
100
- Not considering memory usage
101

© Seth Hobson · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…