Package: scalene
Scalene: a Python CPU+GPU+memory profiler with AI-powered optimization proposalsbyEmery Berger,Sam Stern, andJuan Altmayer Pizzorno.Scalene community Slack(tweet from Ian Ozsvald, author ofHigh Performance Python)Scalene web-based user interface:http://plasma-umass.org/scalene-gui/About ScaleneScalene is a high-performance CPU, GPUandmemory 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 suggestionsNoteTo enable AI-powered optimization suggestions, you need to enter anOpenAI keyin the box under "Advanced options".Your account will need to have a positive balance for this to work(check your balance athttps://platform.openai.com/account/usage).Once you've entered your OpenAI key (see above), 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).Quick StartInstalling Scalene:python3 -m pip install -U scaleneorconda install -c conda-forge scaleneUsing 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, installthe Scalene extension from the VS Code Marketplaceor 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 theCommand 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 your_prog.py                             # full profile (outputs to web interface)python3 -m scalene your_prog.py                  # equivalent alternativescalene --cli your_prog.py                       # use the command-line only (no web interface)scalene --cpu your_prog.py                       # only profile CPUscalene --cpu --gpu your_prog.py                 # only profile CPU and GPUscalene --cpu --gpu --memory your_prog.py        # profile everything (same as no options)scalene --reduced-profile your_prog.py           # only profile lines with significant usagescalene --profile-interval 5.0 your_prog.py      # output a new profile every five secondsscalene (Scalene options) --- your_prog.py (...) # use --- to tell Scalene to ignore options after that pointscalene --help                                   # lists all optionsUsing Scalene programmatically in your code:Invoke usingscaleneas above and then:fromscaleneimportscalene_profiler# Turn profiling onscalene_profiler.start()# Turn profiling offscalene_profiler.stop()Using Scalene to profile only specific functions via@profile:Just preface any functions you want to profile with the@profiledecorator and run it with Scalene:# do not import profile!@profiledefslow_function():importtimetime.sleep(3)Web-based GUIScalene 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 fileprofile.htmlis self-contained and can be saved for later use.Scalene OverviewScalene talk (PyCon US 2021)This talkpresented 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!Fast and AccurateScalene isfast. 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 isaccurate. We tested CPU profiler accuracy and found that Scalene is among the most accurate profilers, correctly measuring time taken.Scalene performs profilingat the line levelandper function, pointing to the functions and the specific lines of code responsible for the execution time in your program.CPU profilingScaleneseparates 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.Scalenehighlights hotspots(code accounting for significant percentages of CPU time or memory allocation) in red, making them even easier to spot.Scalene also separates outsystem time, making it easy to find I/O bottlenecks.GPU profilingScalene reportsGPU time(currently limited to NVIDIA-based systems).Memory profilingScaleneprofiles 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 ofmemory consumed by Python code vs. native code.Scalene producesper-linememory profiles.Scaleneidentifies lines with likely memory leaks.Scaleneprofilescopying volume, making it easy to spot inadvertent copying, especially due to crossing Python/library boundaries (e.g., accidentally convertingnumpyarrays into Python arrays, and vice versa).Other featuresScalene can producereduced profiles(via--reduced-profile) that only report lines that consume more than 1% of CPU or perform at least 100 allocations.Scalene supports@profiledecorators to profile only specific functions.When Scalene is profiling a program launched in the background (via&), you cansuspend and resume profiling.Comparison to Other ProfilersPerformance and FeaturesBelow is a table comparing theperformance and featuresof various profilers to Scalene.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 themultiprocessinglibrary --Scalene onlyPython vs. C time: breaks out time spent in Python vs. native code (e.g., libraries) --Scalene onlySystem time: breaks out system time (e.g., sleeping or performing I/O) --Scalene onlyProfiles memory: reports memory consumption per line / functionGPU: reports time spent on an NVIDIA GPU (if present) --Scalene onlyMemory trends: reports memory use over time per line / function --Scalene onlyCopy volume: reports megabytes being copied per second --Scalene onlyDetects leaks: automatically pinpoints lines responsible for likely memory leaks --Scalene onlyOutputIf you include the--clioption, 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-alland only include files with at least a--cpu-percent-thresholdof time).  Here is a snippet frompystone.py.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").ScaleneThe following command runs Scalene on a provided example program.scalene test/testme.pyClick to see all Scalene's options (available by running with--help)%scalene--helpusage: 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/scalenecommand-line:%scalene[options]yourprogram.pyor%python3-mscalene[options]yourprogram.pyin Jupyter, line mode:%scrun[options]statementin 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_INTERVALoutput 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_ONLYprofile 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_THRESHOLDonly report profiles with at least this percent of CPU time (default: 1%)--cpu-sampling-rate CPU_SAMPLING_RATECPU sampling rate (default: every 0.01s)--malloc-threshold MALLOC_THRESHOLDonly report profiles with at least this many allocations (default: 100)When running Scalene in the background, you can suspend/resume profilingfor the process ID that Scalene reports. For example:%python3-mscalene[options]yourprogram.py&Scalene now profiling process 12345to suspend profiling: python3 -m scalene.profile --off --pid 12345to resume profiling:  python3 -m scalene.profile --on  --pid 12345Scalene with JupyterInstructions for installing and using Scalene with Jupyter notebooksThis notebookillustrates the use of Scalene in Jupyter.Installation:!pip install scalene%load_extscaleneLine mode:%scrun[options]statementCell mode:%%scalene[options]code...code...InstallationUsingpip(Mac OS X, Linux, Windows, and WSL2)Scalene is distributed as apippackage and works on Mac OS X, Linux (including Ubuntu inWindows WSL2) and (with limitations) Windows platforms.NoteThe Windows version currently only supports CPU and GPU profiling, but not memory or copy profiling.You can install it as follows:%pipinstall-Uscaleneor%python3-mpipinstall-UscaleneYou may need to install some packages first.Seehttps://stackoverflow.com/a/19344978/4954434for full instructions for all Linux flavors.For Ubuntu/Debian:%sudoaptinstallgitpython3-all-devUsingconda(Mac OS X, Linux, Windows, and WSL2)%condainstall-cconda-forgescaleneScalene is distributed as acondapackage and works on Mac OS X, Linux (including Ubuntu inWindows WSL2) and (with limitations) Windows platforms.NoteThe Windows version currently only supports CPU and GPU profiling, but not memory or copy profiling.On ArchLinuxYou can install Scalene on Arch Linux via theAUR
package. Use your favorite AUR helper, or
manually download thePKGBUILDand runmakepkg -cirsto build. Note that this will placelibscalene.soin/usr/lib; modify the below usage instructions accordingly.Asked QuestionsCan I use Scalene with PyTest?A:Yes! You can run it as follows (for example):python3 -m scalene --- -m pytest your_test.pyIs there any way to get shorter profiles or do more targeted profiling?A:Yes! There are several options:Use--reduced-profileto include only lines and files with memory/CPU/GPU activity.Use--profile-onlyto include only filenames containing specific strings (as in,--profile-only foo,bar,baz).Decorate functions of interest with@profileto have Scalene reportonlythose functions.Turn profiling on and off programmatically by importing Scalene (import scalene) and then turning profiling on and off viascalene_profiler.start()andscalene_profiler.stop(). By default, Scalene runs with profiling on, so to delay profiling until desired, use the--offcommand-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--noreloadoption (seehttps://github.com/plasma-umass/scalene/issues/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 (https://github.com/pytorch/pytorch/issues/57185) that interferes with Scalene (discussion here:https://github.com/plasma-umass/scalene/issues/110), but only on Macs.Technical InformationFor details about how Scalene works, please see the following paper, which won the Jay Lepreau Best Paper Award atOSDI 2023:Triangulating Python Performance Issues with Scalene. (Note that this paper does not include information about the AI-driven proposed optimizations.)To cite Scalene in an academic paper, please use the following:@inproceedings{288540,
author ={Emery D. Berger and Sam Stern and Juan Altmayer Pizzorno},
title ={Triangulating Python Performance Issues with{S}calene}},
booktitle ={{17th USENIX Symposium on Operating Systems Design and Implementation (OSDI 23)}},
year ={2023},
isbn ={978-1-939133-34-2},
address ={Boston, MA},
pages ={51--64},
url ={https://www.usenix.org/conference/osdi23/presentation/berger},
publisher ={USENIX Association},
month = jul}Success StoriesIf you use Scalene to successfully debug a performance problem, pleaseadd a comment to this issue!AcknowledgementsLogo created bySophia 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.