MCPcopy
hub / github.com/plasma-umass/scalene

github.com/plasma-umass/scalene @v2.3.0 sqlite

repository ↗ · DeepWiki ↗ · release v2.3.0 ↗
6,615 symbols 21,855 edges 312 files 829 documented · 13%
README

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

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

Profiler accuracy

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

CPU profiling

  • Scalene separates out time spent in Python from time in native code (including libraries). Most Python programmers aren't going to optimize the performance of native code (which is usually either in the Python implementation or external libraries), so this helps developers focus their optimization efforts on the code they can actually improve.
  • Scalene highlights hotspots (code accounting for significant percentages of CPU time or memory allocation) in red, making them even easier to spot.
  • Scalene also separates out system time, making it easy to find I/O bottlenecks.

GPU profiling

  • Scalene reports GPU time (currently limited to NVIDIA-based systems).

Memory profiling

  • Scalene profiles memory usage. In addition to tracking CPU usage, Scalene also points to the specific lines of code responsible for memory growth. It accomplishes this via an included specialized memory allocator.
  • Scalene separates out the percentage of memory consumed by Python code vs. native code.
  • Scalene produces per-line memory profiles.
  • Scalene identifies lines with likely memory leaks.
  • Scalene profiles copying volume, making it easy to spot inadvertent copying, especially due to crossing Python/library boundaries (e.g., accidentally converting numpy arrays into Python arrays, and vice versa).

Other features

  • Scalene can produce reduced profiles (via --reduced-profile) that only report lines that consume more than 1% of CPU or perform at least 100 allocations.
  • Scalene supports @profile decorators to profile only specific functions.
  • When Scalene is profiling a program launched in the background (via &), you can suspend and resume profiling.

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

  • Slowdown: the slowdown when running a benchmark from the Pyperformance suite. Green means less than 2x overhead. Scalene's overhead is just a 35% slowdown.

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

  • Lines or functions: does the profiler report information only for entire functions, or for every line -- Scalene does both.
  • Unmodified Code: works on unmodified code.
  • Threads: supports Python threads.
  • Multiprocessing: supports use of the multiprocessing library -- Scalene only
  • Python vs. C time: breaks out time spent in Python vs. native code (e.g., libraries) -- Scalene only
  • System time: breaks out system time (e.g., sleeping or performing I/O) -- Scalene only
  • Profiles memory: reports memory consumption per line / function
  • GPU: reports time spent on an NVIDIA GPU (if present) -- Scalene only
  • Memory trends: reports memory use over time per line / function -- Scalene only
  • Copy volume: reports megabytes being copied per second -- Scalene only
  • Detects leaks: automatically pinpoints lines responsible for likely memory leaks -- Scalene only

Output

If you include the --cli option, Scalene prints annotated source code for the program being profi

Extension points exported contracts — how you extend this code

OpenAIErrorResponse (Interface)
(no doc)
scalene/scalene-gui/openai.ts
OpenAIChoice (Interface)
(no doc)
scalene/scalene-gui/openai.ts
OpenAIResponse (Interface)
(no doc)
scalene/scalene-gui/openai.ts
OpenAIModel (Interface)
(no doc)
scalene/scalene-gui/openai.ts
OpenAIModelsResponse (Interface)
(no doc)
scalene/scalene-gui/openai.ts

Core symbols most depended-on inside this repo

push
called by 803
scalene/runningstats.py
map
called by 350
scalene/scalene-gui/scalene-gui-bundle.js
e
called by 256
scalene/scalene-gui/scalene-gui-bundle.js
add
called by 248
scalene/scalene-gui/scalene-gui-bundle.js
get
called by 214
scalene/scalene-gui/scalene-gui-bundle.js
n
called by 197
scalene/scalene-gui/scalene-gui-bundle.js
t
called by 188
scalene/scalene-gui/scalene-gui-bundle.js
append
called by 180
scalene/sorted_reservoir.py

Shape

Function 4,569
Method 1,715
Class 289
Interface 40
Route 2

Languages

TypeScript67%
Python33%

Modules by API surface

scalene/scalene-gui/scalene-gui-bundle.js3,871 symbols
scalene/scalene-gui/bootstrap.bundle.min.js334 symbols
scalene/scalene-gui/scalene-gui.ts84 symbols
tests/test_native_stacks.py73 symbols
scalene/scalene-gui/jquery-3.6.0.slim.min.js70 symbols
scalene/scalene_profiler.py69 symbols
test/original/bm_raytrace.py67 symbols
test/optimized/bm_raytrace.py67 symbols
test/expensive_benchmarks/bm_raytrace.py67 symbols
test/original/bm_richards.py53 symbols
test/optimized/bm_richards.py53 symbols
tests/test_tensorflow_profiler.py50 symbols

Dependencies from manifests, versioned

@aws-sdk/client-bedrock3.687.0 · 1×
@aws-sdk/client-bedrock-runtime3.687.0 · 1×
@aws-sdk/credential-provider-cognito-identity3.687.0 · 1×
@aws-sdk/credential-provider-web-identity3.686.0 · 1×
@aws-sdk/protocol-http3.374.0 · 1×
@aws-sdk/signature-v43.374.0 · 1×
@types/node20.10.0 · 1×
@types/prismjs1.26.0 · 1×
buffer6.0.3 · 1×
esbuild0.24.0 · 1×
typescript5.3.3 · 1×
vega5.30.0 · 1×

For agents

$ claude mcp add scalene \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact