scalene README

项目的 README,来自 github.com/plasma-umass/scalene。合并为一个 markdown 文件:README.md。

scalene

Scalene: a Python CPU+GPU+memory profiler with AI-powered optimization proposals

by Emery Berger, Sam Stern, and Juan Altmayer Pizzorno.

Scalene community SlackScalene community Slack

PyPI Latest ReleaseAnaconda-Server Badge DownloadsAnaconda downloads Downloads Python versionsLicense GitHub Repo stars

Ozsvald tweet

(tweet from Ian Ozsvald, author of High Performance Python)

Semantic Scholar success story

Python Profiler Links to AI to Improve Code Scalene identifies inefficiencies and asks GPT-4 for suggestions, IEEE Spectrum

Episode 172: Measuring Multiple Facets of Python Performance With Scalene, The Real Python podcast

Scalene web-based user interface: https://scalene-gui.github.io/scalene-gui/

About Scalene

Scalene is a high-performance CPU, GPU and memory profiler for Python that does a number of things that other Python profilers do not and cannot do. It runs orders of magnitude faster than many other profilers while delivering far more detailed information. It is also the first profiler ever to incorporate AI-powered proposed optimizations.

AI-powered optimization suggestions

Note

For optimization suggestions, Scalene supports a variety of AI providers, including Amazon Bedrock, Microsoft Azure, OpenAI, and local models via Ollama. To enable AI-powered optimization suggestions from AI providers, you need to select a provider and, if needed, enter your credentials, in the box under "AI Optimization Options". To prefill them from environment variables (such as OPENAI_API_KEY, ANTHROPIC_API_KEY, or AWS_ACCESS_KEY_ID), view the profile with scalene view --api-keys-from-env. To save them instead, use scalene config set anthropic_api_key (it prompts for the key; scalene config --help lists the settings), which stores them in ~/.scalene/config.json, readable only by you. Saved settings are used without any flag; with --api-keys-from-env, environment variables override them, and whatever you type into the GUI overrides both. Either way, the keys are passed only to your local browser session and are never written into the HTML file.

AI Optimization Options

Once you've entered your key and any other needed data, click on the lightning bolt (⚡) beside any line or the explosion (💥) for an entire region of code to generate a proposed optimization. Click on a proposed optimization to copy it to the clipboard.

example proposed optimization

You can click as many times as you like on the lightning bolt or explosion, and it will generate different suggested optimizations. Your mileage may vary, but in some cases, the suggestions are quite impressive (e.g., order-of-magnitude improvements).

Quick Start

Installing Scalene:

python3 -m pip install -U scalene

or

conda install -c conda-forge scalene

Using Scalene:

After installing Scalene, you can use Scalene at the command line, or as a Visual Studio Code extension.

Using the Scalene VS Code Extension:

First, install the Scalene extension from the VS Code Marketplace or by searching for it within VS Code by typing Command-Shift-X (Mac) or Ctrl-Shift-X (Windows). Once that's installed, click Command-Shift-P or Ctrl-Shift-P to open the Command Palette. Then select "Scalene: AI-powered profiling..." (you can start typing Scalene and it will pop up if it's installed). Run that and, assuming your code runs for at least a second, a Scalene profile will appear in a webview.

Screenshot 2023-09-20 at 7 09 06 PM
Commonly used command-line options:

Scalene uses a verb-based command structure with two main commands: run (to profile) and view (to display results), plus config (to save AI provider settings for the GUI).

# Profile a program (saves to scalene-profile.json)
scalene run your_prog.py
python3 -m scalene run your_prog.py              # equivalent alternative

# View a profile
scalene view                                     # open profile in browser
scalene view --cli                               # view in terminal
scalene view --html                              # save to scalene-profile.html
scalene view --standalone                        # save as self-contained HTML

# Common profiling options
scalene run --cpu-only your_prog.py              # only profile CPU (faster)
scalene run -o results.json your_prog.py         # custom output filename
scalene run -c config.yaml your_prog.py          # load options from config file

# Pass arguments to your program (use --- separator)
scalene run your_prog.py --- --arg1 --arg2

# Get help
scalene --help                                   # main help
scalene run --help                               # profiling options
scalene run --help-advanced                      # advanced profiling options
scalene view --help                              # viewing options
Using a YAML configuration file:

You can store Scalene options in a YAML configuration file and load them with -c or --config:

scalene run -c scalene.yaml your_prog.py

Example scalene.yaml:

# Output options
outfile: my-profile.json

# Profiling mode (use only one)
cpu-only: true              # CPU profiling only (faster)
# gpu: true                 # Include GPU profiling
# memory: true              # Include memory profiling

# Filter what gets profiled
profile-only: "mypackage,mymodule"    # Only profile these paths
profile-exclude: "tests,venv"          # Exclude these paths
profile-all: false                     # Profile all code, not just target

# Performance tuning
cpu-percent-threshold: 1     # Min CPU% to report (default: 1)
cpu-sampling-rate: 0.01      # Sampling interval in seconds
malloc-threshold: 100        # Min allocations to report

# Other options
use-virtual-time: false      # Measure CPU time only (not I/O)
stacks: true                 # Collect stack traces (default: true)
memory-leak-detector: true   # Detect likely memory leaks

Command-line arguments override config file settings.

Using Scalene programmatically in your code:

Invoke using scalene as above and then:

from scalene import scalene_profiler

# Turn profiling on
scalene_profiler.start()

# your code

# Turn profiling off
scalene_profiler.stop()
from scalene.scalene_profiler import enable_profiling

with enable_profiling():
    # do something
Using Scalene to profile only specific functions via @profile:

Just preface any functions you want to profile with the @profile decorator and run it with Scalene:

# do not import profile!

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

Web-based GUI

Scalene has both a CLI and a web-based GUI (demo here).

By default, once Scalene has profiled your program, it will open a tab in a web browser with an interactive user interface (all processing is done locally). Hover over bars to see breakdowns of CPU and memory consumption, and click on underlined column headers to sort the columns. The GUI works fully offline with no internet connection required.

Use scalene view --standalone to generate a completely self-contained HTML file with all assets embedded, perfect for sharing or archiving.

Scalene web GUI

Scalene Overview

Scalene talk (PyCon US 2021)

This talk presented at PyCon 2021 walks through Scalene's advantages and how to use it to debug the performance of an application (and provides some technical details on its internals). We highly recommend watching this video!

Scalene presentation at PyCon 2021

Fast and Accurate

Profiler accuracy

CPU profiling

GPU profiling

Memory profiling

Async profiling

Scalene attributes wall-clock await time to the exact line where the coroutine is suspended, alongside the mean and peak number of coroutines waiting concurrently on that line. This makes it easy to spot serialized I/O (long await, low concurrency) versus genuinely-parallel fan-out (long await, high concurrency). The await column in the GUI draws a clockwise pie wedge per line; bigger wedges mean more time spent suspended on that await.

Async profiling is on by default; pass --no-async to disable it. Overhead on non-async code is negligible (one frozenset lookup per signal, and sys.monitoring callbacks never fire when no coroutines are running).

Per-line await time pies

Stack views (call stacks, memory flame chart, timeline)

When Scalene is run with --stacks (the default — pass --no-stacks to disable), it captures stitched Python + native (C/C++) stacks at every CPU and allocation sample, and presents them three ways in the GUI:

All three views are collapsible and resizable; expand them via the disclosure triangles at the bottom of the GUI.

Other features

Comparison to Other Profilers

Performance and Features

Below is a table comparing the performance and features of various profilers to Scalene.

Performance and feature comparison

Scalene has all of the following features, many of which only Scalene supports:

Output

If you include the --cli option, Scalene prints annotated source code for the program being profiled (as text, JSON (--json), or HTML (--html)) and any modules it uses in the same directory or subdirectories (you can optionally have it --profile-all and only include files with at least a --cpu-percent-threshold of time). Here is a snippet from pystone.py.

Example profile

Scalene

The following command runs Scalene on a provided example program.

scalene test/testme.py
Click to see all Scalene's options (available by running with --help)
% scalene --help
Scalene: a high-precision CPU and memory profiler, version 1.5.51 (2025.01.29)
https://github.com/plasma-umass/scalene

commands:
  run     Profile a Python program (saves to scalene-profile.json)
  view    View an existing profile in browser or terminal
  config  Save AI provider settings (API keys, models) for the GUI

examples:
  % scalene run your_program.py              # profile, save to scalene-profile.json
  % scalene view                             # view scalene-profile.json in browser
  % scalene view --cli                       # view profile in terminal

in Jupyter, line mode:
  %scrun [options] statement

in Jupyter, cell mode:
  %%scalene [options]
   your code here

% scalene run --help
Profile a Python program with Scalene.

examples:
  % scalene run prog.py                 # profile, save to scalene-profile.json
  % scalene run -o my.json prog.py      # save to custom file
  % scalene run --cpu-only prog.py      # profile CPU only (faster)
  % scalene run -c scalene.yaml prog.py # load options from config file
  % scalene run prog.py --- --arg       # pass args to program
  % scalene run --help-advanced         # show advanced options

options:
  -h, --help            show this help message and exit
  -o, --outfile OUTFILE output file (default: scalene-profile.json)
  --cpu-only            only profile CPU time (no memory/GPU)
  -c, --config FILE     load options from YAML config file
  --help-advanced       show advanced options

% scalene run --help-advanced
Advanced options for scalene run:

background profiling:
  Use --off to start with profiling disabled, then control it from another terminal:
    % scalene run --off prog.py          # start with profiling off
    % python3 -m scalene.profile --on  --pid <PID>   # resume profiling
    % python3 -m scalene.profile --off --pid <PID>   # suspend profiling

options:
  --profile-all         profile all code, not just the target program
  --profile-only PATH   only profile files containing these strings (comma-separated)
  --profile-exclude PATH exclude files containing these strings (comma-separated)
  --profile-system-libraries  profile Python stdlib and installed packages (default: skip)
  --gpu                 profile GPU time and memory
  --memory              profile memory usage
  --stacks              collect stack traces (default: on)
  --no-stacks           disable stack-trace collection
  --profile-interval N  output profiles every N seconds (default: inf)
  --use-virtual-time    measure only CPU time, not I/O or blocking
  --cpu-percent-threshold N  only report lines with at least N% CPU (default: 1%)
  --cpu-sampling-rate N CPU sampling rate in seconds (default: 0.01)
  --allocation-sampling-window N  allocation sampling window in bytes
  --malloc-threshold N  only report lines with at least N allocations (default: 100)
  --program-path PATH   directory containing code to profile
  --memory-leak-detector  EXPERIMENTAL: report likely memory leaks
  --on                  start with profiling on (default)
  --off                 start with profiling off

% scalene view --help
View an existing Scalene profile.

examples:
  % scalene view                    # open in browser
  % scalene view --cli              # view in terminal
  % scalene view --html             # save to scalene-profile.html
  % scalene view --standalone       # save as single self-contained HTML file
  % scalene view myprofile.json     # open specific profile in browser
  % scalene view --api-keys-from-env  # prefill AI API keys from env vars

options:
  -h, --help     show this help message and exit
  --cli          display profile in the terminal
  --html         save to scalene-profile.html (no browser)
  --standalone   save as a single self-contained HTML file with all
                 assets embedded (implies --html)
  -r, --reduced  only show lines with activity (--cli mode)
  --api-keys-from-env
                 prefill AI provider API keys from environment variables,
                 overriding settings saved with `scalene config`; served
                 only to the local browser, never written to HTML

Scalene with Jupyter

Instructions for installing and using Scalene with Jupyter notebooks

This notebook illustrates the use of Scalene in Jupyter.

Installation:

!pip install scalene
%load_ext scalene

Line mode:

%scrun [options] statement

Cell mode:

%%scalene [options]
code...
code...

Scalene with pytest

Instructions for profiling a test suite with pytest --scalene

Scalene ships a pytest plugin, so profiling a test run is just a flag on your usual pytest command — no throwaway driver script. The plugin is registered automatically when you install Scalene; it does nothing unless you pass --scalene.

pytest --scalene                     # profile the whole session (CPU)
pytest --scalene -k test_hot         # profile only the selected tests
pytest --scalene --scalene-memory    # profile CPU *and* memory

The profile is written to scalene-profile.json, which you view the usual way:

scalene view                         # open in browser
scalene view --cli                   # view in terminal

To profile only certain tests, mark them with @pytest.mark.scalene. Unmarked tests still run, but with profiling suspended:

import pytest

@pytest.mark.scalene
def test_the_slow_one():
    ...

Options:

Option Effect
--scalene Profile CPU, in-process (no re-launch)
--scalene-memory Also profile memory (re-runs pytest under scalene run)
--scalene-gpu Also profile GPU time and memory (also re-runs)
--scalene-outfile PATH Where to write the profile
--scalene-args='...' Extra arguments to forward to scalene run

Memory and GPU profiling re-run pytest under scalene run automatically, because allocation tracking needs Scalene's native library loaded before the interpreter starts. Equivalently, you can drive it the other way around:

scalene run -m pytest your_test.py

Using pytest-xdist: distributed runs (-n 4, --dist) are supported for both CPU and memory. Because the tests execute in worker subprocesses, Scalene re-runs the session under scalene run so that each worker is profiled as a child process; their statistics are then merged into the single scalene-profile.json:

pytest --scalene -n 4                # CPU, every worker, merged
pytest --scalene-memory -n 4         # CPU + memory, every worker, merged

Note that reported CPU percentages are relative to wall-clock time, which for a parallel run is the elapsed time of the whole session — so per-line percentages are lower than in a serial run even though the ranking is the same.

Installation

Using pip (Mac OS X, Linux, Windows, and WSL2)

Scalene is distributed as a pip package and works on Mac OS X, Linux (including Ubuntu in Windows WSL2) and Windows platforms.

Note for Windows users

Starting with Scalene 2.0, Windows supports full memory profiling. If you encounter issues, ensure you have the Visual C++ Redistributable installed. If building from source, you will need Visual C++ Build Tools and CMake.

You can install it as follows:

  % pip install -U scalene

or

  % python3 -m pip install -U scalene

You may need to install some packages first.

See https://stackoverflow.com/a/19344978/4954434 for full instructions for all Linux flavors.

For Ubuntu/Debian:

  % sudo apt install git python3-all-dev
Using conda (Mac OS X, Linux, Windows, and WSL2)
  % conda install -c conda-forge scalene

Scalene is distributed as a conda package and works on Mac OS X, Linux (including Ubuntu in Windows WSL2) and Windows platforms.

Note for Windows users

Starting with Scalene 2.0, Windows supports full memory profiling. If you encounter issues, ensure you have the Visual C++ Redistributable installed.

On ArchLinux

You can install Scalene on Arch Linux via the AUR package. Use your favorite AUR helper, or manually download the PKGBUILD and run makepkg -cirs to build. Note that this will place libscalene.so in /usr/lib; modify the below usage instructions accordingly.

Frequently Asked Questions

Can I use Scalene with PyTest?

A: Yes! Scalene ships a pytest plugin, so the simplest way is to add the --scalene flag to your usual pytest command:

pytest --scalene your_test.py            # profile CPU; writes scalene-profile.json
pytest --scalene -k test_hot             # profile only the selected tests
pytest --scalene --scalene-memory        # profile CPU *and* memory

This profiles the whole test session and writes scalene-profile.json, which you can open with scalene view. To profile only specific tests, mark them with @pytest.mark.scalene — only marked tests are then profiled:

import pytest

@pytest.mark.scalene
def test_the_slow_one():
    ...

Useful options: --scalene-outfile PATH (where to write the profile), --scalene-gpu (also profile the GPU), and --scalene-args='...' (forward extra arguments such as --profile-all to Scalene).

Memory and GPU profiling (--scalene-memory / --scalene-gpu) re-run pytest under scalene run automatically, because allocation tracking requires Scalene's native library to be preloaded.

You can also drive it the other way around, which is equivalent to --scalene-memory:

scalene run -m pytest your_test.py

Distributed pytest-xdist runs work too (pytest --scalene -n 4, with or without --scalene-memory): Scalene profiles each worker and merges the results into one profile.

See Scalene with pytest for the full set of options.

Is there any way to get shorter profiles or do more targeted profiling?

A: Yes! There are several options:

  1. Use --reduced-profile to include only lines and files with memory/CPU/GPU activity.
  2. Use --profile-only to include only filenames containing specific strings (as in, --profile-only foo,bar,baz).
  3. Decorate functions of interest with @profile to have Scalene report only those functions.
  4. Turn profiling on and off programmatically by importing Scalene profiler (from scalene import scalene_profiler) and then turning profiling on and off via scalene_profiler.start() and scalene_profiler.stop(). By default, Scalene runs with profiling on, so to delay profiling until desired, use the --off command-line option (scalene run --off yourprogram.py).
How do I run Scalene in PyCharm?

A: In PyCharm, you can run Scalene at the command line by opening the terminal at the bottom of the IDE and running a Scalene command (e.g., scalene run <your program>). Then use scalene view --html to generate an HTML file (scalene-profile.html) that you can view in the IDE.

How do I use Scalene with Django?

A: Pass in the --noreload option (see https://github.com/plasma-umass/scalene/issues/178).

Does Scalene work with gevent/Greenlets?

A: Yes! Put the following code in the beginning of your program, or modify the call to monkey.patch_all as below:

from gevent import monkey
monkey.patch_all(thread=False)
How do I use Scalene with PyTorch on the Mac?

A: Scalene works with PyTorch version 1.5.1 on Mac OS X. There's a bug in newer versions of PyTorch (https://github.com/pytorch/pytorch/issues/57185) that interferes with Scalene (discussion here: https://github.com/plasma-umass/scalene/issues/110), but only on Macs.

Technical Information

For details about how Scalene works, please see the following paper, which won the Jay Lepreau Best Paper Award at OSDI 2023: Triangulating Python Performance Issues with Scalene. (Note that this paper does not include information about the AI-driven proposed optimizations.)

To cite Scalene in an academic paper, please use the following:
@inproceedings{288540,
author = {Emery D. Berger and Sam Stern and Juan Altmayer Pizzorno},
title = {Triangulating Python Performance Issues with {S}calene},
booktitle = {{17th USENIX Symposium on Operating Systems Design and Implementation (OSDI 23)}},
year = {2023},
isbn = {978-1-939133-34-2},
address = {Boston, MA},
pages = {51--64},
url = {https://www.usenix.org/conference/osdi23/presentation/berger},
publisher = {USENIX Association},
month = jul
}

Success Stories

If you use Scalene to successfully debug a performance problem, please add a comment to this issue!

Acknowledgements

Logo created by Sophia Berger.

This material is based upon work supported by the National Science Foundation under Grant No. 1955610. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation.

scalene (plasma-umass/scalene)

正在搜索数据库…

这是什么?Scalene 是一个高性能的 Python CPU、GPU 和内存性能分析器(profiler)。它也是第一个提供 AI 优化建议的性能分析器,可以通过 OpenAI、Azure、Bedrock 或本地 Ollama 模型等供应商来实现。
它能做哪些其他 Python 性能分析器做不到的事?它的对比表中有多项功能标为 Scalene 独有:区分 Python 与原生 C/C++ 代码的耗时、系统耗时、GPU 耗时、逐行内存变化趋势、拷贝数据量、内存泄漏检测、逐行 async/await 归因,以及拼接在一起的 Python + 原生调用栈。
我该怎么用它来分析一个脚本?运行 'scalene run yourprogram.py',结果会保存到 scalene-profile.json,再用 'scalene view' 就能在本地网页界面里交互式查看('scalene view --cli' 则直接输出到终端)。在 Jupyter 中可以使用 %scrun 或 %%scalene 魔法命令。
用它需要 API 密钥吗?只有 AI 优化建议才需要:选择一个供应商——Amazon Bedrock、Microsoft Azure、OpenAI,或通过 Ollama 使用本地模型——然后在 'AI Optimization Options' 下填入凭据。性能分析本身不需要密钥,也不用联网。
性能分析会让我的程序慢多少?通常不多:Scalene 采用采样而不是插桩,开销一般不超过 10-20%(往往更低);它的基准测试显示减速约 35%。
网页界面会把我的代码或性能分析数据发送到别处吗?不会。Scalene 会打开一个本地网页界面,所有处理都在本地完成,完全支持离线使用;'scalene view --standalone' 还能生成一个独立的 HTML 文件,方便分享。
GPU 性能分析在任何显卡上都能用吗?不能——GPU 耗时统计目前只支持 NVIDIA 显卡的系统。
它能告诉我内存泄漏是哪里来的吗?可以——它会生成逐行的内存使用分析,并自动指出最可能造成泄漏的代码行。它还会报告拷贝数据量(MB/s),从而暴露无意的拷贝,比如不小心把 numpy 数组转成了 Python 数组。
调用栈视图显示的是什么?使用 --stacks(默认开启)时,Scalene 会在每次采样时捕获拼接好的 Python + 原生(C/C++)调用栈,并以三种方式展示:调用栈火焰图、按内存加权的火焰图(宽度与分配的 MB 数成正比),以及包含 GC、I/O 和 GIL 轨道的墙钟时间线。
它能和 VS Code 或 Jupyter 集成吗?两者都支持。有一个 VS Code 扩展,其 'Scalene: AI-powered profiling...' 命令会在 webview 中运行性能分析;在 Jupyter 里可以使用 %scrun 行魔法命令或 %%scalene 单元魔法命令。
我可以只分析某个函数,而不是整个程序吗?可以——在任何函数前面加上 @profile 装饰器,再在 Scalene 下运行程序,就能只得到该函数的详细结果。还有 --reduced-profile 选项,只报告 CPU 占用超过 1% 或分配次数不少于 100 次的代码行。
大小
20.3 MB
星标
13.6K
时长
6年
提交 · 90 天