mcpField
O
optimizing-python-performance

optimizing-python-performance

github.com/wdm0006開発109134 回インストール2 日前に更新
リポジトリ

optimizing-python-performance について

Python 開発者向けのパフォーマンス最適化スキルです。プロファイリング、メモリー分析、ベンチマーク、コード改善の指針を扱います。

主な機能

  1. 01PyInstrument と cProfile による分析
  2. 02tracemalloc によるメモリー分析
  3. 03pytest-benchmark の利用
  4. 04アルゴリズムとデータ構造の指針
  5. 05最適化前のチェックリスト

活用シーン

  1. 01Python コードの実行ボトルネック特定
  2. 02メモリー割り当ての調査
  3. 03ベンチマーク結果と性能回帰の測定

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/wdm0006/python-skills --skill optimizing-python-performance

インストール後、Claude Code で/optimizing-python-performanceを入力して読み込まれたか確認します。

同梱ファイルBENCHMARKS.mdPROFILING.md

詳細

Python のパフォーマンス最適化

プロファイリングのクイックスタート

# PyInstrument (statistical, readable output)
python -m pyinstrument script.py

# cProfile (detailed, built-in)
python -m cProfile -s cumulative script.py

# Memory profiling
uv add --dev memray
memray run script.py
memray flamegraph memray-*.bin

PyInstrument の使い方

from pyinstrument import Profiler

profiler = Profiler()
profiler.start()
result = my_function()
profiler.stop()
print(profiler.output_text(unicode=True, color=True))

メモリ分析

import tracemalloc

tracemalloc.start()
# ... code ...
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno')[:10]:
    print(stat)

ベンチマーク(pytest-benchmark)

def test_encode_benchmark(benchmark):
    result = benchmark(encode, 37.7749, -122.4194)
    assert len(result) == 12
pytest tests/ --benchmark-only
pytest tests/ --benchmark-compare

よく使われる最適化

# Use set for membership (O(1) vs O(n))
valid = set(items)
if item in valid: ...

# Use deque for queue operations
from collections import deque
queue = deque()
queue.popleft()  # O(1) vs list.pop(0) O(n)

# Use generators for large data
def process(items):
    for item in items:
        yield transform(item)

# Cache expensive computations
from functools import lru_cache

@lru_cache(maxsize=1000)
def expensive(x):
    return compute(x)

# String building
result = "".join(str(x) for x in items)  # Not += in loop

アルゴリズムの計算量

操作listsetdict
検索O(n)O(1)O(1)
挿入O(1)O(1)O(1)
削除O(n)O(1)O(1)

詳しい手法については、以下を参照してください:

最適化チェックリスト

Before Optimizing:
- [ ] Confirm there's a real problem
- [ ] Profile to find actual bottleneck
- [ ] Establish baseline measurements

Process:
- [ ] Algorithm improvements first
- [ ] Then data structures
- [ ] Then implementation details
- [ ] Measure after each change

After:
- [ ] Add benchmarks to prevent regression
- [ ] Verify correctness unchanged
- [ ] Document why optimization needed

詳細情報

このスキルは、Will McGinnis による 高品質な Python ライブラリ開発ガイド の「パフォーマンス」セクションに基づいています。より詳しい内容については、以下の記事をご覧ください:

コメント