Python performance optimization

From findscripter/everything-skills · View interactive version

Python performance optimization is an AI agent skill from the GitHub repository findscripter/everything-skills. 当 Python 应用变慢、CPU/内存吃紧、需要在优化前定位真实瓶颈时使用;先用 cProfile/line_profiler/memory_profiler/py-spy 剖析热点,再按算法→数据结构→缓存→向量化→并行的次序优化并做前后基准对比;不适用于功能正确性 bug、非 Python 代码或线上分布式链路追踪;触发词:Python 性能、cProfile、py-spy、lru_cache、内存泄漏、慢。

How to use this skill

Skill file

何时使用

适用:

不该用(负边界):

铁律:先测量,后优化(profile before optimizing);只优化高频热路径,避免对罕见路径过度优化;先保证清晰,再谈性能。

步骤 / 指令

  1. 建基线:用 timeit/time.perf_counter 或下方 @benchmark 装饰器记录优化前耗时/内存,作为对照。
  2. 定位热点(按需选工具):
  1. 按收益排序优化(先大后小):算法/数据结构 → 实现层惯用法 → 缓存 → 向量化(NumPy) → 并行(多进程/异步)。
  2. 复测对比:用同一基线脚本测优化后,报告加速比;用 pytest-benchmark --benchmark-compare 做回归。
  3. 守门:在 CI/关键路径加基准测试,防止性能回退。

优化决策速查:

示例

cProfile 定位 CPU 热点:

import cProfile, pstats
from pstats import SortKey

profiler = cProfile.Profile()
profiler.enable()
main()                      # 待剖析入口
profiler.disable()

stats = pstats.Stats(profiler)
stats.sort_stats(SortKey.CUMULATIVE)
stats.print_stats(10)       # Top 10
stats.dump_stats("profile_output.prof")

命令行剖析与查看:

python -m cProfile -o output.prof script.py
python -m pstats output.prof   # 交互:sort cumtime / stats 10

线上进程无侵入采样(py-spy):

pip install py-spy
py-spy top  --pid 12345                 # 实时热点
py-spy record -o profile.svg --pid 12345 # 生成火焰图
py-spy dump --pid 12345                  # 当前调用栈

缓存递归——lru_cache 量级提速:

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n-1) + fib(n-2)
# fib.cache_info() 查看命中率

通用基准装饰器:

import time
from functools import wraps

def benchmark(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.perf_counter()-start:.6f}s")
        return result
    return wrapper

检测内存泄漏(tracemalloc 前后快照对比):

import tracemalloc
tracemalloc.start()
snap1 = tracemalloc.take_snapshot()
run_suspect_code()
snap2 = tracemalloc.take_snapshot()
for stat in snap2.compare_to(snap1, 'lineno')[:10]:
    print(stat)
tracemalloc.stop()

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.