コンテンツにスキップ

Scalene で Python のプロファイリングを行う

Scalene とは

Scalene は Python の高性能な CPU、GPU、メモリプロファイラで次のような特徴を持つ。

  • CLI と Web ベースの GUI を備えており、CPU、GPU、メモリのプロファイリングが可能。
  • Scalene は高精度で高速であり、CPU プロファイリングでは Python とネイティブコードの時間を分離して計測できる。
  • GPU プロファイリング、メモリ使用量の詳細な分析、メモリリークの特定もサポート
  • Web ベースの GUI では、CPU およびメモリの消費の詳細な分析が可能で、提案された最適化も表示
  • AI 搭載のプロファイラで、提案された最適化を生成する。AI 搭載の最適化提案を有効にするには、OpenAI キーが必要。

インストール

pip install scalene

使い方

プログラム全体のプロファイリング

scalene [options] yourprogram.py [yourprogramoptions]

オプション

scalene your_prog.py                             # full profile (outputs to web interface)
python3 -m scalene your_prog.py                  # equivalent alternative

scalene --cli your_prog.py                       # use the command-line only (no web interface)

scalene --cpu your_prog.py                       # only profile CPU
scalene --cpu --gpu your_prog.py                 # only profile CPU and GPU
scalene --cpu --gpu --memory your_prog.py        # profile everything (same as no options)

scalene --reduced-profile your_prog.py           # only profile lines with significant usage
scalene --profile-interval 5.0 your_prog.py      # output a new profile every five seconds

scalene (Scalene options) --- your_prog.py (...) # use --- to tell Scalene to ignore options after that point
scalene --help

プログラムの特定の範囲のプロファイリング

1
2
3
4
5
6
7
from scalene import scalene_profiler

# Turn profiling on
scalene_profiler.start()

# Turn profiling off
scalene_profiler.stop()

関数のプロファイリング

関数に @profile デコレータを付けると、その関数のプロファイリングが行われる。

1
2
3
4
5
6
# do not import profile!

@profile
def slow_function():
    import time
    time.sleep(3)

使ってみての注意点

原因は特定できてないが、一部のプログラムは cli とstart()stop()を使ったプロファイリングができなかった。 この場合は関数に@profileを付けることでプロファイリングができた。