• Stars
    star
    11,180
  • Rank 2,847 (Top 0.06 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 4 years ago
  • Updated 6 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Scalene: a high-performance, high-precision CPU, GPU, and memory profiler for Python with AI-powered optimization proposals

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 BadgeDownloads Downloads Python versions License

Ozsvald tweet

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

Semantic Scholar success story

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. To enable these, you need to enter an OpenAI key:

Scalene advanced options

Once a valid key is entered, 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:

Commonly used options:
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                                   # lists all options
Using Scalene programmatically in your code:

Invoke using scalene as above and then:

from scalene import scalene_profiler

# Turn profiling on
scalene_profiler.start()

# Turn profiling off
scalene_profiler.stop()
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 generated file profile.html is self-contained and can be saved for later use.

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

  • Memory usage at the top: Visualized by "sparklines", memory consumption over the runtime of the profiled code.
  • "Time Python": How much time was spent in Python code.
  • "native": How much time was spent in non-Python code (e.g., libraries written in C/C++).
  • "system": How much time was spent in the system (e.g., I/O).
  • "GPU": (not shown here) How much time spent on the GPU, if your system has an NVIDIA GPU installed.
  • "Memory Python": How much of the memory allocation happened on the Python side of the code, as opposed to in non-Python code (e.g., libraries written in C/C++).
  • "net": Positive net memory numbers indicate total memory allocation in megabytes; negative net memory numbers indicate memory reclamation.
  • "timeline / %": Visualized by "sparklines", memory consumption generated by this line over the program runtime, and the percentages of total memory activity this line represents.
  • "Copy (MB/s)": The amount of megabytes being copied per second (see "About Scalene").

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
     usage: scalene [-h] [--outfile OUTFILE] [--html] [--reduced-profile]
                    [--profile-interval PROFILE_INTERVAL] [--cpu-only]
                    [--profile-all] [--profile-only PROFILE_ONLY]
                    [--use-virtual-time]
                    [--cpu-percent-threshold CPU_PERCENT_THRESHOLD]
                    [--cpu-sampling-rate CPU_SAMPLING_RATE]
                    [--malloc-threshold MALLOC_THRESHOLD]
     
     Scalene: a high-precision CPU and memory profiler.
     https://github.com/plasma-umass/scalene
     
     command-line:
        % scalene [options] yourprogram.py
     or
        % python3 -m scalene [options] yourprogram.py
     
     in Jupyter, line mode:
        %scrun [options] statement
     
     in Jupyter, cell mode:
        %%scalene [options]
        code...
        code...
     
     optional arguments:
       -h, --help            show this help message and exit
       --outfile OUTFILE     file to hold profiler output (default: stdout)
       --html                output as HTML (default: text)
       --reduced-profile     generate a reduced profile, with non-zero lines only (default: False)
       --profile-interval PROFILE_INTERVAL
                             output profiles every so many seconds (default: inf)
       --cpu-only            only profile CPU time (default: profile CPU, memory, and copying)
       --profile-all         profile all executed code, not just the target program (default: only the target program)
       --profile-only PROFILE_ONLY
                             profile only code in filenames that contain the given strings, separated by commas (default: no restrictions)
       --use-virtual-time    measure only CPU time, not time spent in I/O or blocking (default: False)
       --cpu-percent-threshold CPU_PERCENT_THRESHOLD
                             only report profiles with at least this percent of CPU time (default: 1%)
       --cpu-sampling-rate CPU_SAMPLING_RATE
                             CPU sampling rate (default: every 0.01s)
       --malloc-threshold MALLOC_THRESHOLD
                             only report profiles with at least this many allocations (default: 100)
     
     When running Scalene in the background, you can suspend/resume profiling
     for the process ID that Scalene reports. For example:
     
        % python3 -m scalene [options] yourprogram.py &
      Scalene now profiling process 12345
        to suspend profiling: python3 -m scalene.profile --off --pid 12345
        to resume profiling:  python3 -m scalene.profile --on  --pid 12345

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

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 (with limitations) Windows platforms. (Note: the Windows version isn't yet complete; it currently only supports CPU profiling.)

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 Homebrew (Mac OS X)

As an alternative to pip, you can use Homebrew to install the current version of Scalene from this repository:

  % brew tap plasma-umass/scalene
  % brew install --head plasma-umass/scalene/scalene
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.

Asked Questions

Can I use Scalene with PyTest?

A: Yes! You can run it as follows (for example):

python3 -m scalene --- -m pytest your_test.py

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 (import scalene) 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 (python3 -m scalene --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., python -m scalene <your program>). Use the options --cli, --html, and --outfile <your output.html> to generate an HTML file that you can then view in the IDE.

How do I use Scalene with Django?

A: Pass in the --noreload option (see #178).

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 (pytorch/pytorch#57185) that interferes with Scalene (discussion here: #110), but only on Macs.

Technical Information

For details about how Scalene works, please see the following paper, accepted to appear at OSDI 2023: Triangulating Python Performance Issues with Scalene. Note that this paper currently does not include information about the AI-driven proposed optimizations.

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.

More Repositories

1

coz

Coz: Causal Profiling
C
3,753
star
2

browsix

Browsix is a Unix-like operating system for the browser.
JavaScript
3,117
star
3

doppio

Breaks the browser language barrier (includes a plugin-free JVM).
TypeScript
2,150
star
4

Mesh

A memory allocator that automatically reduces the memory footprint of C/C++ applications.
C++
1,618
star
5

ChatDBG

ChatDBG - AI-assisted debugging. Uses AI to answer 'why'
C++
669
star
6

BLeak

BLeak: Automatically Debugging Memory Leaks in Web Applications
TypeScript
409
star
7

slipcover

Near Zero-Overhead Python Code Coverage
Python
405
star
8

cwhy

"See why!" Explains and suggests fixes for compile-time errors for C, C++, C#, Go, Java, LaTeX, PHP, Python, Ruby, Rust, and TypeScript
C++
266
star
9

sqlwrite

SQLwrite: AI in your DBMS! Automatically converts natural language queries to SQL.
C
106
star
10

NextDoor

Graph Sampling using GPU
Cuda
47
star
11

DataDebug

Excel 2010/2013 add-in that automatically finds errors in spreadsheets
C#
46
star
12

systemgo

Init system in Go, intended to run on Browsix and other Unix-like OS. Part of GSoC 2016 project.
Go
31
star
13

sheriff

Sheriff consists of two tools: Sheriff-Detect, a false-sharing detector, and Sheriff-Protect, a false-sharing eliminator that you can link with your code to eliminate false sharing.
C++
29
star
14

DoubleTake

Evidence-based dynamic analysis: a fast checker for memory errors.
C
21
star
15

commentator

Automatically comments Python code, adding docstrings and type annotations, with optional translation to other languages.
Python
19
star
16

Predator

Predator: Predictive False Sharing Detection
C
19
star
17

memory-landscape

The space of memory management research and systems produced by the PLASMA lab (https://plasma-umass.org).
16
star
18

snakefish

parallel Python
Python
13
star
19

parcel

An Excel formula parser
C#
12
star
20

entroprise

measure entropy of memory allocators
C++
12
star
21

Rehearsal

Rehearsal: A Configuration Verification Tool for Puppet
Scala
12
star
22

coverup

Automatic AI-powered test suite generator
Python
12
star
23

Hound

Hound memory leak detector
C++
11
star
24

smash-project

Smash compressing allocator project
C++
10
star
25

browsix-spec

JavaScript
9
star
26

Archipelago

Archipelago memory allocator
C
8
star
27

simplesocket

A simple socket wrapper for C++.
C++
8
star
28

pythoness

Pythoness: use natural language to define Python functions.
Python
7
star
29

compsci631

Support code for Programming Languages (COMPSCI631)
OCaml
7
star
30

Tortoise

Tortoise: Interactive System Configuration Repair
Scala
6
star
31

scalene-gui

Scalene web GUI
JavaScript
5
star
32

transparentFS

TransparentFS code, paper, and slides
C
5
star
33

homebrew-scalene

Homebrew tap for Scalene (emeryberger/scalene)
Ruby
4
star
34

GSoC

Description of our Google Summer of Code projects for 2015
4
star
35

llm-utils

Utilities for our LLM projects (CWhy, ChatDBG, ...).
Python
4
star
36

HeapToss

HeapToss is an LLVM compiler pass that moves stack variables that may escape their declaring function's context into the heap.
3
star
37

GSoC-2013

Google Summer of Code 2013
2
star
38

jsvm

JavaScript
2
star
39

plasma-umass.github.io

home page
HTML
2
star
40

spl

Rust
2
star
41

doppio_jcl

Scripts that produce a version of the Java Class Library and Java Home in a way that is compatible with DoppioJVM.
TypeScript
2
star
42

nextdoor-eurosys21

HTML
1
star
43

mesh-testsuite

C
1
star
44

proto

probabilistic race tolerance
C
1
star
45

ChatSheet

Python
1
star
46

custom-public

Jupyter Notebook
1
star
47

wasm-gc-template

C++
1
star
48

typissed

Generates MTurk typo jobs
C#
1
star
49

scalene-benchmarks

Benchmarks comparing Scalene with other commonly-used profilers
Python
1
star
50

emcc_control

C
1
star
51

transparentMM

Transparent memory management
1
star