python-performance

$npx mdskill add seaworld008/Commonly-used-high-value-skills/python-performance

Profile and optimize Python code for speed and memory.

  • Identifies performance bottlenecks in Python services and scripts.
  • Uses cProfile, line_profiler, Py-spy, memory_profiler, and tracemalloc.
  • Recommends concurrency patterns based on I/O vs CPU-bound analysis.
  • Provides actionable optimization steps and profiling reports.

SKILL.md

.github/skills/python-performanceView on GitHub ↗
---
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 分析
```bash
python -m cProfile -s cumtime script.py
```

### 使用 Py-spy 生成火焰图
```bash
# 采样 30 秒并生成 svg 火焰图
py-spy record -o profile.svg --duration 30 --pid <PID>
```

### Asyncio 并发请求模板
```python
import asyncio
import httpx

async def fetch_url(client, url):
    response = await client.get(url)
    return response.status_code

async def main(urls):
    async with httpx.AsyncClient() as client:
        tasks = [fetch_url(client, url) for url in urls]
        results = await asyncio.gather(*tasks)
        print(f"Finished {len(results)} requests")

if __name__ == "__main__":
    urls = ["https://example.com" for _ in range(100)]
    asyncio.run(main(urls))
```

### Numba 加速数值计算
```python
from numba import jit
import numpy as np

@jit(nopython=True)
def sum_of_squares(arr):
    res = 0
    for i in range(len(arr)):
        res += arr[i] ** 2
    return res

data = np.random.rand(10_000_000)
# 第一次调用会有编译开销,后续飞快
print(sum_of_squares(data))
```

## 边界与限制

- **过度优化**: 不要为了极小的性能提升而牺牲代码的可读性和可维护性(Premature optimization is the root of all evil)。
- **库的局限性**: 某些 C 扩展库如果不小心在多线程中使用,可能会导致严重的内存错误或死锁。
- **GIL 限制**: Python 不适合极高频率的锁竞争场景。
- **冷启动开销**: 像 Numba 这种 JIT 工具在第一次运行或编译时会有显著延迟。
- **硬件局限**: 性能调优不能替代由于带宽、磁盘 I/O 或数据库性能不足导致的系统瓶颈。

---
*Generated by Skill Master - Professional Edition*

More from seaworld008/Commonly-used-high-value-skills

SkillDescription
agent-hubMulti-agent collaboration plugin that spawns N parallel subagents competing on the same task via git worktree isolation. Agents work independently, results are evaluated by metric or LLM judge, and the best branch is merged. Use when: user wants multiple approaches tried in parallel — code optimization, content variation, research exploration, or any task that benefits from parallel competition. Requires: a git repo.
andrej-karpathy-skillsKarpathy-inspired coding discipline for AI agents: think before coding, keep changes simple, edit surgically, and define verifiable success criteria before implementation.
arenaSpecialist orchestrating codex exec / Antigravity CLI through dual paradigms — COMPETE (multi-variant comparison, select best) and COLLABORATE (decompose tasks across engines, integrate). Supports Solo/Team/Quick execution modes.
azure-kubernetesPlan, create, and configure production-ready Azure Kubernetes Service (AKS) clusters. Covers Day-0 checklist, SKU selection (Automatic vs Standard), networking options (private API server, Azure CNI Overlay, egress configuration), security, and operations (autoscaling, upgrade strategy, cost analysis). WHEN: create AKS environment, provision AKS, enable AKS observability, design AKS networking, choose AKS SKU, secure AKS, optimize AKS, AKS spot nodes, AKS cluster-autoscaler, rightsize AKS pod, pod rightsizing, over-provisioned AKS pod, pod resource requests and limits, Vertical Pod Autoscaler, VPA recommendations.
azure-kubernetes-automatic-readinessAssess Kubernetes workloads and cluster configuration for AKS Automatic compatibility. Identifies incompatibilities, generates fixes, and guides migration from AKS Standard to AKS Automatic. WHEN: migrate to AKS Automatic, check AKS Automatic readiness, validate manifests for Automatic, assess cluster for Automatic compatibility, fix deployment for Automatic compatibility, identify AKS Automatic migration blockers, is my cluster ready for AKS Automatic.
cc-devops-skillsSRE, DevOps, Kubernetes, CI/CD, PromQL, Terraform, Docker, and incident operations playbook for building reliable delivery and operations workflows.
chatgpt-appsBuild, scaffold, refactor, and troubleshoot ChatGPT Apps SDK applications that combine an MCP server and widget UI. Use when Codex needs to design tools, register UI resources, wire the MCP Apps bridge or ChatGPT compatibility APIs, apply Apps SDK metadata or CSP or domain settings, or produce a docs-aligned project scaffold. Prefer a docs-first workflow by invoking the openai-docs skill or OpenAI developer docs MCP tools before generating code.
clayAI 3D model generation agent. Generates text-to-3D and image-to-3D code (Python/JS/OpenSCAD) using Meshy, Tripo, Hunyuan3D, Rodin, Sloyd, and Stability APIs. Handles game pipeline integration, LOD, retopology, UV, and QC validation.
codeql-security-scanner用于通过 CodeQL 执行语义代码扫描、安全查询、自定义规则、SARIF 报告和 GitHub Code Scanning 集成。
complyRegulatory compliance and audit agent. Maps business regulatory requirements (SOC2/PCI-DSS/HIPAA/ISO 27001), checks control implementations, designs audit trails, and implements Policy as Code. Use when compliance auditing is needed.