Debian Codegraph @

README.md

raw symbols SCIP
1 ![scalene](https://github.com/plasma-umass/scalene/raw/master/docs/scalene-icon-white.png)
2
3 # Scalene: a Python CPU+GPU+memory profiler with AI-powered optimization proposals
4
5 by [Emery Berger](https://emeryberger.com), [Sam Stern](https://samstern.me/), and [Juan Altmayer Pizzorno](https://github.com/jaltmayerpizzorno).
6
7 [![Scalene community Slack](https://github.com/plasma-umass/scalene/raw/master/docs/images/slack-logo.png)](https://join.slack.com/t/scaleneprofil-jge3234/shared_invite/zt-110vzrdck-xJh5d4gHnp5vKXIjYD3Uwg)[Scalene community Slack](https://join.slack.com/t/scaleneprofil-jge3234/shared_invite/zt-110vzrdck-xJh5d4gHnp5vKXIjYD3Uwg)
8
9 [![PyPI Latest Release](https://img.shields.io/pypi/v/scalene.svg)](https://pypi.org/project/scalene/)[![Anaconda-Server Badge](https://img.shields.io/conda/v/conda-forge/scalene)](https://anaconda.org/conda-forge/scalene) [![Downloads](https://static.pepy.tech/badge/scalene)](https://pepy.tech/project/scalene)[![Anaconda downloads](https://img.shields.io/conda/d/conda-forge/scalene?logo=conda)](https://anaconda.org/conda-forge/scalene) [![Downloads](https://static.pepy.tech/badge/scalene/month)](https://pepy.tech/project/scalene) ![Python versions](https://img.shields.io/pypi/pyversions/scalene.svg?style=flat-square)[![Visual Studio Code Extension version](https://img.shields.io/visual-studio-marketplace/v/emeryberger.scalene?logo=visualstudiocode)](https://marketplace.visualstudio.com/items?itemName=EmeryBerger.scalene) ![License](https://img.shields.io/github/license/plasma-umass/scalene) [![GitHub Repo stars](https://img.shields.io/github/stars/plasma-umass/scalene?style=social)](https://github.com/plasma-umass/scalene)
10
11
12 ![Ozsvald tweet](https://github.com/plasma-umass/scalene/raw/master/docs/Ozsvald-tweet.png)
13
14 (tweet from Ian Ozsvald, author of [_High Performance Python_](https://smile.amazon.com/High-Performance-Python-Performant-Programming/dp/1492055026/ref=sr_1_1?crid=texbooks))
15
16 ![Semantic Scholar success story](https://github.com/plasma-umass/scalene/raw/master/docs/semantic-scholar-success.png)
17
18 [_Python Profiler Links to AI to Improve Code Scalene identifies inefficiencies and asks GPT-4 for suggestions_](https://spectrum.ieee.org/python-programming), IEEE Spectrum
19
20 [Episode 172: Measuring Multiple Facets of Python Performance With Scalene](https://realpython.com/podcasts/rpp/172/), The Real Python podcast
21
22 ***Scalene web-based user interface:*** [https://scalene-gui.github.io/scalene-gui/](https://scalene-gui.github.io/scalene-gui/)
23
24 ## About Scalene
25
26 Scalene is a high-performance CPU, GPU *and* memory profiler for
27 Python that does a number of things that other Python profilers do not
28 and cannot do. It runs orders of magnitude faster than many other
29 profilers while delivering far more detailed information. It is also
30 the first profiler ever to incorporate AI-powered proposed
31 optimizations.
32
33 ### AI-powered optimization suggestions
34
35 > **Note**
36 >
37 > For optimization suggestions, Scalene supports a variety of AI providers, including [Amazon Bedrock](https://aws.amazon.com/bedrock), [Microsoft Azure](https://azure.microsoft.com/en-us/), [OpenAI](https://openai.com), and local models via [Ollama](https://ollama.com/). 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".
38 >
39 > <img width="607" height="316" alt="AI Optimization Options" src="https://github.com/user-attachments/assets/3c803237-063f-481a-8624-5c1d7f205c8a" />
40
41
42 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.
43
44 <img width="571" alt="example proposed optimization" src="https://user-images.githubusercontent.com/1612723/211639968-37cf793f-3290-43d1-9282-79e579558388.png">
45
46 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).
47
48 ### Quick Start
49
50 #### Installing Scalene:
51
52 ```console
53 python3 -m pip install -U scalene
54 ```
55
56 or
57
58 ```console
59 conda install -c conda-forge scalene
60 ```
61
62 #### Using Scalene:
63
64 After installing Scalene, you can use Scalene at the command line, or as a Visual Studio Code extension.
65
66 <details>
67 <summary>
68 Using the Scalene VS Code Extension:
69 </summary>
70
71
72 First, install <a href="https://marketplace.visualstudio.com/items?itemName=EmeryBerger.scalene">the Scalene extension from the VS Code Marketplace</a> 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 <a href="https://code.visualstudio.com/docs/getstarted/userinterface">Command Palette</a>. Then select <b>"Scalene: AI-powered profiling..."</b> (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.
73
74 <img width="734" alt="Screenshot 2023-09-20 at 7 09 06 PM" src="https://github.com/plasma-umass/scalene/assets/1612723/7e78e3d2-e649-4f02-86fd-0da2a259a1a4">
75
76 </details>
77
78 <details>
79 <summary>
80 Commonly used command-line options:
81 </summary>
82
83 ```console
84 scalene your_prog.py # full profile (outputs to web interface)
85 python3 -m scalene your_prog.py # equivalent alternative
86
87 scalene --cli your_prog.py # use the command-line only (no web interface)
88
89 scalene --cpu your_prog.py # only profile CPU
90 scalene --cpu --gpu your_prog.py # only profile CPU and GPU
91 scalene --cpu --gpu --memory your_prog.py # profile everything (same as no options)
92
93 scalene --reduced-profile your_prog.py # only profile lines with significant usage
94 scalene --profile-interval 5.0 your_prog.py # output a new profile every five seconds
95
96 scalene (Scalene options) --- your_prog.py (...) # use --- to tell Scalene to ignore options after that point
97 scalene --help # lists all options
98 ```
99
100 </details>
101
102 <details>
103 <summary>
104 Using Scalene programmatically in your code:
105 </summary>
106
107 Invoke using `scalene` as above and then:
108
109 ```Python
110 from scalene import scalene_profiler
111
112 # Turn profiling on
113 scalene_profiler.start()
114
115 # your code
116
117 # Turn profiling off
118 scalene_profiler.stop()
119 ```
120
121 ```Python
122 from scalene.scalene_profiler import enable_profiling
123
124 with enable_profiling():
125 # do something
126 ```
127
128 </details>
129
130 <details>
131 <summary>
132 Using Scalene to profile only specific functions via <code>@profile</code>:
133 </summary>
134
135 Just preface any functions you want to profile with the `@profile` decorator and run it with Scalene:
136
137 ```Python
138 # do not import profile!
139
140 @profile
141 def slow_function():
142 import time
143 time.sleep(3)
144 ```
145
146 </details>
147
148 #### Web-based GUI
149
150 Scalene has both a CLI and a web-based GUI [(demo here)](https://scalene-gui.github.io/scalene-gui/).
151
152 By default, once Scalene has profiled your program, it will open a
153 tab in a web browser with an interactive user interface (all processing is done
154 locally). Hover over bars to see breakdowns of CPU and memory
155 consumption, and click on underlined column headers to sort the
156 columns. The generated file `profile.html` is self-contained and can be saved for later use.
157
158 [![Scalene web GUI](https://raw.githubusercontent.com/plasma-umass/scalene/master/docs/scalene-gui-example.png)](https://raw.githubusercontent.com/plasma-umass/scalene/master/docs/scalene-gui-example-full.png)
159
160
161 ## Scalene Overview
162
163 ### Scalene talk (PyCon US 2021)
164
165 [This talk](https://youtu.be/5iEf-_7mM1k) 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!
166
167 [![Scalene presentation at PyCon 2021](https://raw.githubusercontent.com/plasma-umass/scalene/master/docs/images/scalene-video-img.png)](https://youtu.be/5iEf-_7mM1k "Scalene presentation at PyCon 2021")
168
169 ### Fast and Accurate
170
171 - 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).
172
173 - Scalene is **accurate**. We tested CPU profiler accuracy and found that Scalene is among the most accurate profilers, correctly measuring time taken.
174
175 ![Profiler accuracy](https://github.com/plasma-umass/scalene/raw/master/docs/cpu-accuracy-comparison.png)
176
177 - 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.
178
179 ### CPU profiling
180
181 - 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.
182 - Scalene **highlights hotspots** (code accounting for significant percentages of CPU time or memory allocation) in red, making them even easier to spot.
183 - Scalene also separates out **system time**, making it easy to find I/O bottlenecks.
184
185 ### GPU profiling
186
187 - Scalene reports **GPU time** (currently limited to NVIDIA-based systems).
188
189 ### Memory profiling
190
191 - 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.
192 - Scalene separates out the percentage of **memory consumed by Python code vs. native code**.
193 - Scalene produces **_per-line_ memory profiles**.
194 - Scalene **identifies lines with likely memory leaks**.
195 - 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).
196
197 ### Other features
198
199 - 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.
200 - Scalene supports `@profile` decorators to profile only specific functions.
201 - When Scalene is profiling a program launched in the background (via `&`), you can **suspend and resume profiling**.
202
203 # Comparison to Other Profilers
204
205 ## Performance and Features
206
207 Below is a table comparing the **performance and features** of various profilers to Scalene.
208
209 ![Performance and feature comparison](https://raw.githubusercontent.com/plasma-umass/scalene/master/docs/images/profiler-comparison.png)
210
211 - **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.
212
213 Scalene has all of the following features, many of which only Scalene supports:
214
215 - **Lines or functions**: does the profiler report information only for entire functions, or for every line -- Scalene does both.
216 - **Unmodified Code**: works on unmodified code.
217 - **Threads**: supports Python threads.
218 - **Multiprocessing**: supports use of the `multiprocessing` library -- _Scalene only_
219 - **Python vs. C time**: breaks out time spent in Python vs. native code (e.g., libraries) -- _Scalene only_
220 - **System time**: breaks out system time (e.g., sleeping or performing I/O) -- _Scalene only_
221 - **Profiles memory**: reports memory consumption per line / function
222 - **GPU**: reports time spent on an NVIDIA GPU (if present) -- _Scalene only_
223 - **Memory trends**: reports memory use over time per line / function -- _Scalene only_
224 - **Copy volume**: reports megabytes being copied per second -- _Scalene only_
225 - **Detects leaks**: automatically pinpoints lines responsible for likely memory leaks -- _Scalene only_
226
227 ## Output
228
229 If you include the `--cli` option, Scalene prints annotated source code for the program being profiled
230 (as text, JSON (`--json`), or HTML (`--html`)) and any modules it
231 uses in the same directory or subdirectories (you can optionally have
232 it `--profile-all` and only include files with at least a
233 `--cpu-percent-threshold` of time). Here is a snippet from
234 `pystone.py`.
235
236 ![Example profile](https://raw.githubusercontent.com/plasma-umass/scalene/master/docs/images/sample-profile-pystone.png)
237
238 * **Memory usage at the top**: Visualized by "sparklines", memory consumption over the runtime of the profiled code.
239 * **"Time Python"**: How much time was spent in Python code.
240 * **"native"**: How much time was spent in non-Python code (e.g., libraries written in C/C++).
241 * **"system"**: How much time was spent in the system (e.g., I/O).
242 * **"GPU"**: (not shown here) How much time spent on the GPU, if your system has an NVIDIA GPU installed.
243 * **"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++).
244 * **"net"**: Positive net memory numbers indicate total memory allocation in megabytes; negative net memory numbers indicate memory reclamation.
245 * **"timeline / %"**: Visualized by "sparklines", memory consumption generated by this line over the program runtime, and the percentages of total memory activity this line represents.
246 * **"Copy (MB/s)"**: The amount of megabytes being copied per second (see "About Scalene").
247
248 ## Scalene
249
250 The following command runs Scalene on a provided example program.
251
252 ```console
253 scalene test/testme.py
254 ```
255
256 <details>
257 <summary>
258 Click to see all Scalene's options (available by running with <code>--help</code>)
259 </summary>
260
261 ```console
262 % scalene --help
263 usage: scalene [-h] [--outfile OUTFILE] [--html] [--reduced-profile]
264 [--profile-interval PROFILE_INTERVAL] [--cpu-only]
265 [--profile-all] [--profile-only PROFILE_ONLY]
266 [--use-virtual-time]
267 [--cpu-percent-threshold CPU_PERCENT_THRESHOLD]
268 [--cpu-sampling-rate CPU_SAMPLING_RATE]
269 [--malloc-threshold MALLOC_THRESHOLD]
270
271 Scalene: a high-precision CPU and memory profiler.
272 https://github.com/plasma-umass/scalene
273
274 command-line:
275 % scalene [options] yourprogram.py
276 or
277 % python3 -m scalene [options] yourprogram.py
278
279 in Jupyter, line mode:
280 %scrun [options] statement
281
282 in Jupyter, cell mode:
283 %%scalene [options]
284 code...
285 code...
286
287 optional arguments:
288 -h, --help show this help message and exit
289 --outfile OUTFILE file to hold profiler output (default: stdout)
290 --html output as HTML (default: text)
291 --reduced-profile generate a reduced profile, with non-zero lines only (default: False)
292 --profile-interval PROFILE_INTERVAL
293 output profiles every so many seconds (default: inf)
294 --cpu-only only profile CPU time (default: profile CPU, memory, and copying)
295 --profile-all profile all executed code, not just the target program (default: only the target program)
296 --profile-only PROFILE_ONLY
297 profile only code in filenames that contain the given strings, separated by commas (default: no restrictions)
298 --use-virtual-time measure only CPU time, not time spent in I/O or blocking (default: False)
299 --cpu-percent-threshold CPU_PERCENT_THRESHOLD
300 only report profiles with at least this percent of CPU time (default: 1%)
301 --cpu-sampling-rate CPU_SAMPLING_RATE
302 CPU sampling rate (default: every 0.01s)
303 --malloc-threshold MALLOC_THRESHOLD
304 only report profiles with at least this many allocations (default: 100)
305
306 When running Scalene in the background, you can suspend/resume profiling
307 for the process ID that Scalene reports. For example:
308
309 % python3 -m scalene [options] yourprogram.py &
310 Scalene now profiling process 12345
311 to suspend profiling: python3 -m scalene.profile --off --pid 12345
312 to resume profiling: python3 -m scalene.profile --on --pid 12345
313 ```
314 </details>
315
316 ### Scalene with Jupyter
317
318 <details>
319 <summary>
320 Instructions for installing and using Scalene with Jupyter notebooks
321 </summary>
322
323 [This notebook](https://nbviewer.jupyter.org/github/plasma-umass/scalene/blob/master/docs/scalene-demo.ipynb) illustrates the use of Scalene in Jupyter.
324
325 Installation:
326
327 ```console
328 !pip install scalene
329 %load_ext scalene
330 ```
331
332 Line mode:
333
334 ```console
335 %scrun [options] statement
336 ```
337
338 Cell mode:
339
340 ```console
341 %%scalene [options]
342 code...
343 code...
344 ```
345 </details>
346
347 ## Installation
348
349 <details open>
350 <summary>Using <code>pip</code> (Mac OS X, Linux, Windows, and WSL2)</summary>
351
352 Scalene is distributed as a `pip` package and works on Mac OS X, Linux (including Ubuntu in [Windows WSL2](https://docs.microsoft.com/en-us/windows/wsl/wsl2-index)) and (with limitations) Windows platforms.
353
354 > **Note**
355 >
356 > The Windows version currently only supports CPU and GPU profiling, but not memory or copy profiling.
357 >
358
359 You can install it as follows:
360 ```console
361 % pip install -U scalene
362 ```
363
364 or
365 ```console
366 % python3 -m pip install -U scalene
367 ```
368
369 You may need to install some packages first.
370
371 See https://stackoverflow.com/a/19344978/4954434 for full instructions for all Linux flavors.
372
373 For Ubuntu/Debian:
374
375 ```console
376 % sudo apt install git python3-all-dev
377 ```
378 </details>
379
380 <details>
381 <summary>Using <code>conda</code> (Mac OS X, Linux, Windows, and WSL2)</summary>
382
383 ```console
384 % conda install -c conda-forge scalene
385 ```
386
387 Scalene is distributed as a `conda` package and works on Mac OS X, Linux (including Ubuntu in [Windows WSL2](https://docs.microsoft.com/en-us/windows/wsl/wsl2-index)) and (with limitations) Windows platforms.
388
389 > **Note**
390 >
391 > The Windows version currently only supports CPU and GPU profiling, but not memory or copy profiling.
392 >
393 </details>
394
395 <details>
396 <summary>On ArchLinux</summary>
397
398 You can install Scalene on Arch Linux via the [AUR
399 package](https://aur.archlinux.org/packages/python-scalene-git/). Use your favorite AUR helper, or
400 manually download the `PKGBUILD` and run `makepkg -cirs` to build. Note that this will place
401 `libscalene.so` in `/usr/lib`; modify the below usage instructions accordingly.
402 </details>
403
404 # Frequently Asked Questions
405
406 <details>
407 <summary>
408 Can I use Scalene with PyTest?
409 </summary>
410
411 **A:** Yes! You can run it as follows (for example):
412
413 `python3 -m scalene --- -m pytest your_test.py`
414
415 </details>
416
417 <details>
418 <summary>
419 Is there any way to get shorter profiles or do more targeted profiling?
420 </summary>
421
422 **A:** Yes! There are several options:
423
424 1. Use `--reduced-profile` to include only lines and files with memory/CPU/GPU activity.
425 2. Use `--profile-only` to include only filenames containing specific strings (as in, `--profile-only foo,bar,baz`).
426 3. Decorate functions of interest with `@profile` to have Scalene report _only_ those functions.
427 4. Turn profiling on and off programmatically by importing Scalene profiler (`from scalene import scalene_profiler`) 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`).
428 </details>
429
430 <details>
431 <summary>
432 How do I run Scalene in PyCharm?
433 </summary>
434
435 **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.
436 </details>
437
438 <details>
439 <summary>
440 How do I use Scalene with Django?
441 </summary>
442
443 **A:** Pass in the `--noreload` option (see https://github.com/plasma-umass/scalene/issues/178).
444 </details>
445
446
447 <details>
448 <summary>
449 Does Scalene work with gevent/Greenlets?
450 </summary>
451
452 **A:** Yes! Put the following code in the beginning of your program, or modify the call to `monkey.patch_all` as below:
453
454 ```python
455 from gevent import monkey
456 monkey.patch_all(thread=False)
457 ```
458 </details>
459
460
461
462 <details>
463 <summary>
464 How do I use Scalene with PyTorch on the Mac?
465 </summary>
466
467 **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.
468 </details>
469
470 # Technical Information
471
472 For details about how Scalene works, please see the following paper, which won the Jay Lepreau Best Paper Award at [OSDI 2023](https://www.usenix.org/conference/osdi23/presentation/berger): [Triangulating Python Performance Issues with Scalene](https://arxiv.org/pdf/2212.07597). (Note that this paper does not include information about the AI-driven proposed optimizations.)
473
474 <details>
475 <summary>
476 To cite Scalene in an academic paper, please use the following:
477 </summary>
478
479 ```latex
480 @inproceedings{288540,
481 author = {Emery D. Berger and Sam Stern and Juan Altmayer Pizzorno},
482 title = {Triangulating Python Performance Issues with {S}calene},
483 booktitle = {{17th USENIX Symposium on Operating Systems Design and Implementation (OSDI 23)}},
484 year = {2023},
485 isbn = {978-1-939133-34-2},
486 address = {Boston, MA},
487 pages = {51--64},
488 url = {https://www.usenix.org/conference/osdi23/presentation/berger},
489 publisher = {USENIX Association},
490 month = jul
491 }
492 ```
493 </details>
494
495
496 # Success Stories
497
498 If you use Scalene to successfully debug a performance problem, please [add a comment to this issue](https://github.com/plasma-umass/scalene/issues/58)!
499
500
501 # Acknowledgements
502
503 Logo created by [Sophia Berger](https://www.linkedin.com/in/sophia-berger/).
504
505 This material is based upon work supported by the National Science
506 Foundation under Grant No. 1955610. Any opinions, findings, and
507 conclusions or recommendations expressed in this material are those of
508 the author(s) and do not necessarily reflect the views of the National
509 Science Foundation.