Scalene: a high-performance, high-precision CPU, GPU, and memory profiler for Python with AI-powered optimization proposals
Scalene: a high-performance, high-precision CPU, GPU, and memory profiler for Python with AI-powered optimization proposals
by Emery Berger, Sam Stern, and Juan Altmayer Pizzorno. Scalene community Slack
(tweet from Ian Ozsvald, author of High Performance Python)
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/
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.
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".
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.
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).
python3 -m pip install -U scaleneor
conda install -c conda-forge scaleneAfter 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.
Commonly used command-line options:Scalene uses a verb-based command structure with two main commands: run (to profile) and view (to display results).
…You can store Scalene options in a YAML configuration file and load them with -c or --config:
scalene run -c scalene.yaml your_prog.pyExample scalene.yaml:
…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@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)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.
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 is fast. It uses sampling instead of instrumentation or relying on Python's tracing facilities. Its overhead is typically no more than 10-20% (and often less).
Scalene is accurate. We tested CPU profiler accuracy and found that Scalene is among the most accurate profilers, correctly measuring time taken.
Scalene performs profiling at the line level and per function, pointing to the functions and the specific lines of code responsible for the execution time in your program.
numpy arrays into Python arrays, and vice versa).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).
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:
Call stacks — a flame chart of the top stitched stacks across the whole run. Python frames are clickable to jump to source. Native frames are demangled and shown alongside Python frames in the same picture, so you can see exactly which library call is on the hot path.
Memory stacks — a memory-weighted flame chart where frame width is proportional to MB allocated along that call path (not sample count). Useful for finding which call paths are responsible for a program's memory footprint, especially when allocations come from deep inside a library.
Timeline — an icicle/time-series view of the same stitched stacks
laid out left-to-right by wall-clock time, with tracks at the top
marking GC, I/O, and GIL activity. Coroutines appear as [await] task_name frames so you can see when each task ran versus waited.
All three views are collapsible and resizable; expand them via the disclosure triangles at the bottom of the GUI.
--reduced-profile) that only report lines that consume more than 1% of CPU or perform at least 100 allocations.@profile decorators to profile only specific functions.&), you can suspend and resume profiling.scalene view --standalone produces a single self-contained HTML
file you can email or archive.Below is a table comparing the performance and features of various profilers to Scalene.
Scalene has all of the following features, many of which only Scalene supports:
multiprocessing library -- Scalene onlyawait profiling: per-line wall-clock attribution of suspended coroutine time, with mean and peak concurrency -- Scalene onlyReplacementSemLock loses cross-process identity when pickled for spawn/forkserver
Wheels for Python 3.11 on Windows
conda stuck at scalene v 1.5.51
Scalene occasionally hangs at startup on macOS hosted CI runners
how to work with gunicorn?
Allow disabling suggestions from report
No memory profiling on windows (WSL or hyperv virtualization)
Create a `HOWTO` doc
Launch WebUI (and do nothing else)
Scalene doesnt work properly with torchrun / torch.distributed.run