Scalene: a high-performance, high-precision CPU and memory profiler for Python

Overview

scalene

scalene: a high-performance CPU and memory profiler for Python

by Emery Berger

PyPI Latest ReleaseDownloads Downloads Python versions License Twitter Follow

中文版本 (Chinese version)

About Scalene

  % pip install -U scalene

Scalene is a high-performance CPU 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 other profilers while delivering far more detailed information.

  1. 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).
  2. Scalene is precise. Unlike most other Python profilers, Scalene performs CPU profiling at the line level, pointing to the specific lines of code that are responsible for the execution time in your program. This level of detail can be much more useful than the function-level profiles returned by most profilers.
  3. Scalene separates out time spent running in Python from time spent 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.
  4. 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.
  5. Scalene produces per-line memory profiles, making it easier to track down leaks.
  6. 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).
  7. NEW! Scalene now reports the percentage of memory consumed by Python code vs. native code.
  8. NEW! Scalene now highlights hotspots (code accounting for significant percentages of CPU time or memory allocation) in red, making them even easier to spot.
  9. NEW! 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.
  10. NEW! Scalene now also supports @profile decorators to profile only specific functions.

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

Function-granularity profilers report information only for an entire function, while line-granularity profilers (like Scalene) report information for every line

  • Time is either real (wall-clock time), CPU-only, or both.
  • Efficiency: 🟢 = fast, 🟡 = slower, 🔴 = slowest
  • Mem Cons.: tracks memory consumption
  • Unmodified Code: works on unmodified code
  • Threads: works correctly with threads
  • Python/C: separately attributes Python/C time and memory consumption
  • Mem Trend: shows memory usage trends over time
  • Copy Vol.: reports copy volume, the amount of megabytes being copied per second

Output

Scalene prints annotated source code for the program being profiled (either as text or as HTML via the --html option) 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. Scalene is a statistical profiler, meaning that it does sampling, and variance can certainly happen. A longer-running program that allocates and frees more memory will have more stable results.
  • "CPU % Python": How much time was spent in Python code.
  • "CPU % Native": How much time was spent in non-Python code (e.g., libraries written in C/C++).
  • "Mem % 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 (MB)": Positive net memory numbers indicate total memory allocation in megabytes; negative net memory numbers indicate memory reclamation.
  • "Memory usage over time / %": 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").

Using scalene

The following command runs Scalene on a provided example program.

  % scalene test/testme.py

To see all the options, run with --help.

% scalene --help
usage: scalene [-h] [--outfile OUTFILE] [--html] [--reduced-profile]
               [--profile-interval PROFILE_INTERVAL] [--cpu-only]
               [--profile-all] [--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/emeryberger/scalene
        % scalene yourprogram.py

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

Installation

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

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

You can install it as follows:

  % pip install -U scalene

or

  % python3 -m pip install -U scalene

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 emeryberger/scalene
  % brew install --head libscalene

ArchLinux

NEW: You can also 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.

Technical Information

For technical details on Scalene, please see the following paper: Scalene: Scripting-Language Aware Profiling for Python (arXiv link).

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.

You might also like...
Cross-platform lib for process and system monitoring in Python
Cross-platform lib for process and system monitoring in Python

Home Install Documentation Download Forum Blog Funding What's new Summary psutil (process and system utilities) is a cross-platform library for retrie

Prometheus instrumentation library for Python applications

Prometheus Python Client The official Python 2 and 3 client for Prometheus. Three Step Demo One: Install the client: pip install prometheus-client Tw

Line-by-line profiling for Python

line_profiler and kernprof NOTICE: This is the official line_profiler repository. The most recent version of line-profiler on pypi points to this repo

pprofile + matplotlib = Python program profiled as an awesome heatmap!
pprofile + matplotlib = Python program profiled as an awesome heatmap!

pyheat Profilers are extremely helpful tools. They help us dig deep into code, find and understand performance bottlenecks. But sometimes we just want

 System monitor - A python-based real-time system monitoring tool
System monitor - A python-based real-time system monitoring tool

System monitor A python-based real-time system monitoring tool Screenshots Installation Run My project with these commands pip install -r requiremen

GoAccess is a real-time web log analyzer and interactive viewer that runs in a terminal in *nix systems or through your browser.
GoAccess is a real-time web log analyzer and interactive viewer that runs in a terminal in *nix systems or through your browser.

GoAccess What is it? GoAccess is an open source real-time web log analyzer and interactive viewer that runs in a terminal on *nix systems or through y

Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.

starlette context Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automat

ASGI middleware to record and emit timing metrics (to something like statsd)

timing-asgi This is a timing middleware for ASGI, useful for automatic instrumentation of ASGI endpoints. This was developed at GRID for use with our

Glances an Eye on your system. A top/htop alternative for GNU/Linux, BSD, Mac OS and Windows operating systems.
Glances an Eye on your system. A top/htop alternative for GNU/Linux, BSD, Mac OS and Windows operating systems.

Glances - An eye on your system Summary Glances is a cross-platform monitoring tool which aims to present a large amount of monitoring information thr

Releases(v1.4.0)
Owner
Emery Berger
Professor of Computer Science, UMass Amherst. Co-director of @plasma-umass.
Emery Berger
Sampling profiler for Python programs

py-spy: Sampling profiler for Python programs py-spy is a sampling profiler for Python programs. It lets you visualize what your Python program is spe

Ben Frederickson 9.5k Jan 8, 2023
Yet Another Python Profiler, but this time thread&coroutine&greenlet aware.

Yappi Yet Another Python Profiler, but this time thread&coroutine&greenlet aware. Highlights Fast: Yappi is fast. It is completely written in C and lo

Sümer Cip 1k Jan 1, 2023
🚴 Call stack profiler for Python. Shows you why your code is slow!

pyinstrument Pyinstrument is a Python profiler. A profiler is a tool to help you 'optimize' your code - make it faster. It sounds obvious, but to get

Joe Rickerby 5k Jan 1, 2023
Visual profiler for Python

vprof vprof is a Python package providing rich and interactive visualizations for various Python program characteristics such as running time and memo

Nick Volynets 3.9k Dec 19, 2022
Was an interactive continuous Python profiler.

☠ This project is not maintained anymore. We highly recommend switching to py-spy which provides better performance and usability. Profiling The profi

What! Studio 3k Dec 27, 2022
Tracy Profiler module for the Godot Engine

GodotTracy Tracy Profiler module for the Godot Engine git clone --recurse-submodules https://github.com/Pineapple/GodotTracy.git Copy godot_tracy fold

Pineapple Works 17 Aug 23, 2022
Development tool to measure, monitor and analyze the memory behavior of Python objects in a running Python application.

README for pympler Before installing Pympler, try it with your Python version: python setup.py try If any errors are reported, check whether your Pyt

null 996 Jan 1, 2023
Monitor Memory usage of Python code

Memory Profiler This is a python module for monitoring memory consumption of a process as well as line-by-line analysis of memory consumption for pyth

null 3.7k Dec 30, 2022
Monitor Memory usage of Python code

Memory Profiler This is a python module for monitoring memory consumption of a process as well as line-by-line analysis of memory consumption for pyth

Fabian Pedregosa 80 Nov 18, 2022
Automatically monitor the evolving performance of Flask/Python web services.

Flask Monitoring Dashboard A dashboard for automatic monitoring of Flask web-services. Key Features • How to use • Live Demo • Feedback • Documentatio

null 663 Dec 29, 2022