| name | python-performance |
| description | Use when profiling Python code, reducing memory usage, optimizing hot paths, choosing concurrency patterns, or reviewing performance regressions in Python services and scripts. |
| zh_description | 用于 Python 性能分析、内存优化、热点路径调优和并发模式评审。 |
| version | 1.0.0 |
| author | seaworld008 |
| source | skills.sh |
| source_url | https://skills.sh/wshobson/agents/python-performance-optimization |
| license | MIT |
| tags | ["development", "performance", "python"] |
| created_at | 2026-03-27 |
| updated_at | 2026-06-29 |
| quality | 4 |
| complexity | intermediate |
Python Performance Optimization
Python is an incredibly productive language, but it can be slow if not handled correctly. This skill provides a systematic approach to identifying bottlenecks, optimizing memory usage, and choosing the right concurrency model.
触发条件
- 应用程序在生产环境中响应缓慢。
- 系统处理大量数据流时,CPU 或内存占用极高。
- 后台任务队列堆积,吞吐量无法满足业务需求。
- 需要针对特定的核心逻辑进行性能压测与调优。
- 项目正在从原型向高并发、高性能生产环境迁移。
核心能力
1. 性能分析 (Profiling)
在优化之前,必须先进行测量。
- cProfile: 使用标准库进行全局函数调用分析,找出耗时最长的函数。
- line_profiler: 对单个函数进行行级别的分析,精确定位热点代码行。
- Py-spy: 生产环境非侵入式采样分析,生成火焰图。
2. 内存分析与泄漏排查
- Memory Profiler: 逐行监测脚本的内存增量。
- Objgraph: 可视化内存中的对象引用关系,追踪无法回收的循环引用。
- tracemalloc: 标准库提供的内存分配追踪工具,定位泄露源头。
3. asyncio 异步编程
针对 I/O 密集型任务(网络请求、数据库操作、文件读写)。
- Event Loop 管理: 理解单线程并发机制,避免在协程中编写阻塞性代码。
- Gather/Wait/As_completed: 并发调度多个协程的模式。
- 第三方库选择: 优先选择 aiohttp, httpx, motor 等原生支持异步的客户端库。
4. 多进程与多线程选型
- Multi-threading: 适用于 I/O 密集型,受限于 GIL,无法利用多核 CPU 处理计算任务。
- Multi-processing: 适用于 CPU 密集型,通过派生进程绕过 GIL,利用多核计算资源。
- Thread/Process Pool Executor: 标准库提供的池化管理,简化并发逻辑。
5. Cython 与 Numba 加速
当纯 Python 无法满足性能要求时。
- Numba (@jit): 即时编译器,特别适合含有大量循环的数值计算(NumPy 场景)。
- Cython: 将 Python 代码编译为 C/C++ 扩展,显式定义类型,性能可提升数十倍。
6. GIL (Global Interpreter Lock) 理解
- 原理解析: 理解 GIL 为什么存在及其对并发的影响。
- 绕过手段: 使用 C 扩展释放 GIL、使用多进程、或将计算任务下沉到 Rust/C++ 编写的底层库(如 Pandas/Polars)。
7. 数据结构选择与算法优化
- Built-in Collections: 合理使用
dict 的哈希查找、set 的去重、deque 的高效双端队列。
- List Comprehensions: 优先于传统的
for 循环追加。
- Generator: 使用生成器处理海量数据,减少内存占用。
常用命令/模板
使用 cProfile 分析
python -m cProfile -s cumtime script.py