# Python 性能优化 (python-performance-optimization)

> 使用 cProfile、line_profiler、memory_profiler 和 py-spy 分析 Python 代码，并按常见模式优化瓶颈。

- 分类: [性能优化](https://www.myskills.tools/zh/categories/performance/)
- 来源: 社区 · Seth Hobson
- 代码仓库: https://github.com/wshobson/agents/tree/main/plugins/python-development/skills/python-performance-optimization (commit 0f73766)
- SKILL.md: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-performance-optimization/SKILL.md
- 安装命令: `npx skills add wshobson/agents --skill python-performance-optimization`
- 许可证: MIT
- 兼容工具: Claude Code, Codex, Cursor, Copilot, OpenCode
- 权限: read-repo ✓, write-files ✓, shell ✓, network ✗
- 状态: 扫描通过
- 规则扫描无法覆盖所有风险，安装前请阅读此技能的 SKILL.md，确认权限后再使用。

## 核心规则

先做性能分析再优化，以找到真正的瓶颈。

## 执行阶段

1. **计时测量** — 用 time 粗测，用 timeit 获得更准确、可重复的执行时间。
2. **性能剖析** — 用 cProfile 分析 CPU，用 line_profiler 逐行分析，用 memory_profiler 看内存，用 py-spy 分析运行中的生产进程。
3. **优化热点路径** — 聚焦高频代码：用 dict/set 查找、推导式、生成器、内置函数、lru_cache，并批量处理 I/O。
4. **进阶手段** — 数值计算用 NumPy，CPU 密集任务用多进程，I/O 密集任务用异步 I/O，并批量执行和优化数据库查询。

## 权限说明（据 SKILL.md 整理）

| 能力 | 是否需要 | 说明 |
|---|---|---|
| 文件写入 | 需要 | 修改 Python 代码以应用优化模式。 |
| 命令执行 | 需要 | 运行 timeit、cProfile、kernprof、memory_profiler、py-spy 等分析工具。 |
| 网络外发 | 不需要 | 技能未要求访问网络，部分分析工具可能需要事先用 pip 安装。 |

## SKILL.md 头部信息（YAML）

```yaml
---
name: python-performance-optimization
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.
---
```

首页: https://www.myskills.tools/zh/ · URL: https://www.myskills.tools/zh/skills/python-performance-optimization/
