scalene README

The project's README from github.com/plasma-umass/scalene. As one markdown file: 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 versionsVisual Studio Code Extension version License 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".

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).

# 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

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 C

scalene (plasma-umass/scalene)

Searching Database…

13.5K ·GitHub
Что это такое?Scalene — это высокопроизводительный профилировщик для Python, который измеряет нагрузку на CPU, GPU и потребление памяти. Он также стал первым профилировщиком с предложениями по оптимизации на основе ИИ — через провайдеров вроде 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-ключ для работы с ним?Только для ИИ-подсказок: выберите провайдера — Amazon Bedrock, Microsoft Azure, OpenAI или локальную модель через Ollama — и введите данные для доступа в разделе 'AI Optimization Options'. Само профилирование работает без ключа и без интернета.
Насколько профилирование замедлит мою программу?Обычно незначительно: Scalene работает выборкой, а не инструментированием кода, поэтому накладные расходы обычно не превышают 10-20% (часто меньше); в его бенчмарке замедление составило 35%.
Веб-интерфейс отправляет мой код или данные профилирования куда-то?Нет. Scalene открывает вкладку браузера с локальным интерфейсом, где вся обработка идёт на вашем компьютере; он полностью работает офлайн, а команда 'scalene view --standalone' создаёт один самодостаточный HTML-файл, удобный для передачи другим.
Профилирование GPU работает с любой видеокартой?Нет — сейчас данные о времени GPU доступны только для систем на базе NVIDIA.
Может ли он показать, откуда в моей программе утечки памяти?Да — он строит профили памяти построчно и автоматически указывает строки, которые скорее всего вызывают утечки. Кроме того, он показывает объём копирования в МБ/с, что выявляет лишнее копирование — например, случайное преобразование массивов numpy в обычные массивы Python.
Что показывают представления стеков?С флагом --stacks (он включён по умолчанию) Scalene при каждой выборке захватывает объединённые стеки Python + нативный код (C/C++) и показывает их тремя способами: плам граф по стеку вызовов, плам граф с учётом памяти (ширина пропорциональна выделенным МБ) и временную шкалу реального времени с дорожками GC, I/O и GIL.
Он интегрируется с VS Code или Jupyter?С обоими. Есть расширение для VS Code: его команда 'Scalene: AI-powered profiling...' запускает профилирование и показывает результат в webview, а в Jupyter можно использовать line-магию %scrun или cell-магию %%scalene.
Можно ли профилировать одну функцию, а не всю программу?Да — добавьте к любой функции декоратор @profile и запустите программу под Scalene: подробные результаты будут только для неё. Есть и опция --reduced-profile, которая показывает только строки, занимающие более 1% CPU или с минимум 100 аллокациями.
Size
19.5 MB
Stars
13.5K
Age
6y
Commits · 90 Days