././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1706461831.1523867
scalene-1.5.34/ 0000755 0000765 0000024 00000000000 14555505207 012462 5 ustar 00runner staff ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1706461830.8943398
scalene-1.5.34/.github/ 0000755 0000765 0000024 00000000000 14555505207 014022 5 ustar 00runner staff ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/.github/FUNDING.yml 0000644 0000765 0000024 00000000123 14555505126 015633 0 ustar 00runner staff # These are supported funding model platforms
github: [emeryberger, plasma-umass]
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1706461830.895619
scalene-1.5.34/.github/ISSUE_TEMPLATE/ 0000755 0000765 0000024 00000000000 14555505207 016205 5 ustar 00runner staff ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/.github/ISSUE_TEMPLATE/bug_report.md 0000644 0000765 0000024 00000001570 14555505126 020702 0 ustar 00runner staff ---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
Please include a minimum working example if at all possible.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
If you have not yet tried with the repository version (`python3 -m pip install git+https://github.com/plasma-umass/scalene`), please try that before reporting.
**Additional context**
Add any other context about the problem here.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/.github/ISSUE_TEMPLATE/feature_request.md 0000644 0000765 0000024 00000001123 14555505126 021727 0 ustar 00runner staff ---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1706461830.8971713
scalene-1.5.34/.github/workflows/ 0000755 0000765 0000024 00000000000 14555505207 016057 5 ustar 00runner staff ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/.github/workflows/build-and-upload.yml 0000644 0000765 0000024 00000012327 14555505126 021730 0 ustar 00runner staff # https://docs.github.com/en/actions/guides/building-and-testing-python#publishing-to-package-registries
# When executed manually, this will upload a ".devNNN" build to testpypi;
# when executed upon a release, it will upload a regular build to pypi.
#
# For pypi, you need to have the PYPI_USERNAME and PYPI_PASSWORD secrets configured.
# For testpypi, you'll need TESTPYPI_USERNAME and TESTPYPI_PASSWORD.
name: build & upload
on:
release:
types: [ published ]
workflow_dispatch: # manual execution
jobs:
pick-devN:
name: create .devN build date coordinated across all matrix jobs
runs-on: ubuntu-latest
steps:
- run: TZ='America/New_York' date '+%Y%m%d%H%M' > devN.txt
- uses: actions/upload-artifact@v3
with:
name: devN
path: devN.txt
build-and-upload:
needs: pick-devN
strategy:
matrix:
python_version: ['3.8', '3.9', '3.10', '3.11']
plat: ['manylinux2014', 'manylinux_2_28', 'macos-latest', 'windows-latest']
include:
- plat: manylinux2014
os: ubuntu-latest
container: quay.io/pypa/manylinux2014_x86_64 # https://github.com/pypa/manylinux
- plat: manylinux_2_28
os: ubuntu-latest
container: quay.io/pypa/manylinux_2_28_x86_64 # https://github.com/pypa/manylinux
- plat: macos-latest
os: macos-latest
- plat: macos-latest
os: macos-latest
python_version: 3.11
upload_source: true # just need ONE of them to do it
- plat: windows-latest
os: windows-latest
exclude:
- plat: windows-latest
python_version: 3.11
runs-on: ${{ matrix.os }}
container: ${{ matrix.container }}
steps:
- name: get coordinated .devN
uses: actions/download-artifact@v3
with:
name: devN
- name: make dev build if not a release (non-Windows version)
if: github.event_name != 'release' && matrix.os != 'windows-latest'
run: echo "DEV_BUILD=$(cat devN.txt)" >> $GITHUB_ENV # for setup.py
- name: make dev build if not a release (Windows version)
if: github.event_name != 'release' && matrix.os == 'windows-latest'
run: ("DEV_BUILD=" + (get-content devN.txt)) >> $env:GITHUB_ENV # for setup.py
# downgraded to @v3 if using container: https://github.com/actions/checkout/issues/1487
- uses: actions/checkout@v3
if: matrix.container != ''
- uses: actions/checkout@v4
if: matrix.container == ''
- name: Mark workspace safe for git
# needed for container and self-hosted runners; see https://github.com/actions/checkout/issues/766
if: matrix.container != ''
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
# setuptool's bdist uses 'git archive' to find files, and fails silently if it can't,
# leading to missing files in the archive. Run it separately to force a failure in that case.
(cd scalene; git archive --prefix scalene/ HEAD | tar -t > /dev/null)
- name: Set up python (script version)
if: matrix.container == ''
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python_version }}
- name: Set up python (container version)
if: matrix.container != ''
run: |
PYV=`echo "${{ matrix.python_version }}" | tr -d "."`; ls -d -1 /opt/python/cp$PYV*/bin | head -n 1 >> $GITHUB_PATH
cat $GITHUB_PATH
- name: Install dependencies
run: |
pip3 install --upgrade setuptools wheel twine build virtualenv
- name: Work around arm64 support on MacOS
# https://github.com/actions/virtual-environments/issues/2557
if: matrix.os == 'macos-latest'
run: sudo rm -Rf /Library/Developer/CommandLineTools/SDKs/*
- name: Build source dist
if: matrix.upload_source
run: make sdist
- name: Build binary dist
# Invoking with "bash -c" works around the "bash.exe: ... could not find /tmp" issue on Windows.
# The issue is somehow related to git providing a sh.exe (the "git shell")
# See eg https://help.appveyor.com/discussions/problems/1531-having-issues-with-configured-git-bash
run: bash -c "make bdist"
- name: Check that all required platforms are included
if: matrix.os == 'macos-latest'
run: |
for P in x86_64 arm64 arm64e; do
for F in build/lib.*/scalene/*.so ; do
file $F | grep -q "\\b$P\\b"
if [ $? != 0 ]; then
echo "$P missing"
exit 1
fi
done
done
- name: Non-release (dev) upload
if: github.event_name != 'release'
env:
TWINE_REPOSITORY: testpypi
TWINE_USERNAME: ${{ secrets.TESTPYPI_USERNAME }}
TWINE_PASSWORD: ${{ secrets.TESTPYPI_PASSWORD }}
run: twine upload --verbose dist/*
- name: Release upload
if: github.event_name == 'release'
env:
TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
run: twine upload --verbose dist/*
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/.github/workflows/codeql.yml 0000644 0000765 0000024 00000001625 14555505126 020055 0 ustar 00runner staff name: "CodeQL"
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
schedule:
- cron: "28 9 * * 3"
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ cpp, python ]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
queries: +security-and-quality
- name: Autobuild
uses: github/codeql-action/autobuild@v2
if: ${{ matrix.language == 'cpp' || matrix.language == 'python' }}
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{ matrix.language }}"
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/.github/workflows/test-smoketests.yml 0000644 0000765 0000024 00000003460 14555505126 021763 0 ustar 00runner staff name: smoketests
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
workflow_dispatch: # manual execution
jobs:
smoketests:
runs-on: ${{ matrix.os }}
timeout-minutes: 15
strategy:
matrix:
os: [ ubuntu-latest, macos-latest ] # disabling windows-latest for now
python: [ '3.8', '3.9', '3.10', '3.11', '3.12']
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
- name: Work around arm64 support on MacOS
# https://github.com/actions/virtual-environments/issues/2557
if: matrix.os == 'macos-latest'
run: sudo rm -Rf /Library/Developer/CommandLineTools/SDKs/*
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
python -m pip install numpy
- name: Build scalene
run: pip -v install -e .
- name: cpu-only smoke test
run: python test/smoketest.py test/testme.py --cpu-only
- name: multiprocessing smoke test
run: python test/smoketest.py test/multiprocessing_test.py
# Note: test/smoketest.py only handles single JSON, rather than multiple in sequence.
- name: profile-interval smoke test
run: python -m scalene --cli --profile-interval=2 test/testme.py
- name: decorator smoke test
run: python test/smoketest_profile_decorator.py
# Note: This test doesn't need to read an output,
# it is meant to determine if there is an ImportError
# or anything related if relative imports are used.
- name: -m invocation smoketest
run: |
python -m pip install git+https://github.com/sternj/import_stress_test
python -m scalene --cli --- -m import_stress_test
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/.gitignore 0000644 0000765 0000024 00000004523 14555505126 014456 0 ustar 00runner staff # Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# Created by https://www.gitignore.io/api/visualstudiocode
# Edit at https://www.gitignore.io/?templates=visualstudiocode
### VisualStudioCode ###
.vscode/* # Maybe .vscode/**/* instead - see comments
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
### VisualStudioCode Patch ###
# Ignore all local history of files
**/.history
# End of https://www.gitignore.io/api/visualstudiocode
.idea
scalene/libscalene.dylib
scalene/libscalene.dylib.dSYM/Contents/Info.plist
scalene/libscalene.dylib.dSYM/Contents/Resources/DWARF/libscalene.dylib
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1706461830.8976545
scalene-1.5.34/.vscode/ 0000755 0000765 0000024 00000000000 14555505207 014023 5 ustar 00runner staff ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/.vscode/c_cpp_properties.json 0000644 0000765 0000024 00000001337 14555505126 020262 0 ustar 00runner staff {
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**",
"/opt/homebrew/opt/python@3.9/Frameworks/Python.framework/Versions/3.9/include/python3.9"
],
"defines": [],
"macFrameworkPath": [
"/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"
],
"compilerPath": "/usr/bin/clang",
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "macos-clang-arm64",
"configurationProvider": "ms-vscode.makefile-tools"
}
],
"version": 4
} ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/CITATION.cff 0000644 0000765 0000024 00000002111 14555505126 014347 0 ustar 00runner staff cff-version: 1.0.0
message: "If you use or refer to Scalene, please cite it as below."
authors:
- family-names: "Berger"
given-names: "Emery D."
orcid: "https://orcid.org/0000-0002-3222-3271"
- family-names: "Altmayer Pizzorno"
given-names: "Juan"
orcid: "https://orcid.org/0000-0002-1891-2919"
- family-names: "Stern"
given-names: "Sam"
title: "Scalene: a high-performance, high-precision CPU, GPU, and memory profiler for Python"
version: 1.5.9
date-released: 2022-07-24
url: "https://github.com/plasma-umass/scalene"
preferred-citation:
type: conference-paper
authors:
- family-names: "Berger"
given-names: "Emery D."
orcid: "https://orcid.org/0000-0002-3222-3271"
- family-names: "Stern"
given-names: "Sam"
- family-names: "Altmayer Pizzorno"
given-names: "Juan"
orcid: "https://orcid.org/0000-0002-1891-2919"
journal: "17th USENIX Symposium on Operating Systems Design and Implementation (OSDI 2023)"
month: 7
start: 51 # First page number
end: 64 # Last page number
title: "Triangulating Python Performance Issues with Scalene"
year: 2023
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/CODE_OF_CONDUCT.md 0000644 0000765 0000024 00000006432 14555505126 015266 0 ustar 00runner staff # Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at Emery.berger@gmail.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/GNUmakefile 0000644 0000765 0000024 00000006157 14555505126 014545 0 ustar 00runner staff LIBNAME = scalene
PYTHON = python3
PYTHON_SOURCES = scalene/[a-z]*.py
JS_SOURCES = scalene/scalene-gui/*.js
C_SOURCES = src/source/*.cpp src/include/*.h*
.PHONY: black clang-format prettier format upload vendor-deps
# CXXFLAGS = -std=c++14 -g -O0 # FIXME
CXXFLAGS = -std=c++14 -Wall -g -O3 -DNDEBUG -D_REENTRANT=1 -DHL_USE_XXREALLOC=1 -pipe -fno-builtin-malloc -fvisibility=hidden
# CXX = g++
INCLUDES = -Isrc -Isrc/include
INCLUDES := $(INCLUDES) -Ivendor/Heap-Layers -Ivendor/Heap-Layers/wrappers -Ivendor/Heap-Layers/utility
INCLUDES := $(INCLUDES) -Ivendor/printf
# python3-config may not be available in venv and such
INCLUDES := $(INCLUDES) -I$(shell python3 -c "import sysconfig; print(sysconfig.get_path('include'))")
ifeq ($(shell uname -s),Darwin)
LIBFILE := lib$(LIBNAME).dylib
WRAPPER := vendor/Heap-Layers/wrappers/macwrapper.cpp
ifneq (,$(filter $(shell uname -p),arm arm64)) # this means "if arm or arm64"
ARCH := -arch arm64 -arch arm64e
else
ARCH := -arch x86_64
endif
CXXFLAGS := -std=c++14 -Wall -g -O3 -DNDEBUG -D_REENTRANT=1 -DHL_USE_XXREALLOC=1 -pipe -fno-builtin-malloc -fvisibility=hidden -flto -ftls-model=initial-exec -ftemplate-depth=1024 $(ARCH) -compatibility_version 1 -current_version 1 -dynamiclib
SED_INPLACE = -i ''
else # non-Darwin
LIBFILE := lib$(LIBNAME).so
WRAPPER := vendor/Heap-Layers/wrappers/gnuwrapper.cpp
INCLUDES := $(INCLUDES) -I/usr/include/nptl
CXXFLAGS := $(CXXFLAGS) -fPIC -shared -Bsymbolic
RPATH_FLAGS :=
SED_INPLACE = -i
endif
SRC := src/source/lib$(LIBNAME).cpp $(WRAPPER) vendor/printf/printf.cpp
OUTDIR=scalene
all: $(OUTDIR)/$(LIBFILE)
$(OUTDIR)/$(LIBFILE): vendor-deps $(SRC) $(C_SOURCES) GNUmakefile
$(CXX) $(CXXFLAGS) $(INCLUDES) $(SRC) -o $(OUTDIR)/$(LIBFILE) -ldl -lpthread
clean:
rm -f $(OUTDIR)/$(LIBFILE) scalene/*.so scalene/*.dylib
rm -rf $(OUTDIR)/$(LIBFILE).dSYM
rm -rf scalene.egg-info
rm -rf build dist *egg-info
$(WRAPPER) : vendor/Heap-Layers
vendor/Heap-Layers:
cd vendor && git clone https://github.com/emeryberger/Heap-Layers
TMP := $(shell mktemp -d || echo /tmp)
vendor/printf/printf.cpp:
cd vendor && git clone https://github.com/mpaland/printf
cd vendor/printf && ln -s printf.c printf.cpp
sed -e 's/^#define printf printf_/\/\/&/' vendor/printf/printf.h > $(TMP)/printf.h.$$ && mv $(TMP)/printf.h.$$ vendor/printf/printf.h
sed -e 's/^#define vsnprintf vsnprintf_/\/\/&/' vendor/printf/printf.h > $(TMP)/printf.h.$$ && mv $(TMP)/printf.h.$$ vendor/printf/printf.h
vendor/crdp:
mkdir -p vendor && cd vendor && git clone https://github.com/plasma-umass/crdp
vendor-deps: vendor/Heap-Layers vendor/printf/printf.cpp vendor/crdp
mypy:
-mypy --no-warn-unused-ignores $(PYTHON_SOURCES)
format: black clang-format prettier
clang-format:
-clang-format -i $(C_SOURCES) --style=google
black:
-black -l 79 $(PYTHON_SOURCES)
prettier:
-npx prettier -w $(JS_SOURCES)
bdist: vendor-deps
$(PYTHON) -m build --wheel
ifeq ($(shell uname -s),Linux)
auditwheel repair dist/*.whl
rm -f dist/*.whl
mv wheelhouse/*.whl dist/
endif
sdist: vendor-deps
$(PYTHON) -m build --sdist
upload: sdist bdist # to pypi
$(PYTHON) -m twine upload dist/*
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/LICENSE 0000644 0000765 0000024 00000026136 14555505126 013477 0 ustar 00runner staff
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/MANIFEST.in 0000644 0000765 0000024 00000000243 14555505126 014217 0 ustar 00runner staff graft vendor/Heap-Layers
prune vendor/Heap-Layers/.git
graft vendor/printf
prune vendor/printf/.git
graft vendor/crdp
prune vendor/crdp/.git
exclude scalene/old/*
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/Makefile 0000644 0000765 0000024 00000002526 14555505126 014127 0 ustar 00runner staff LIBNAME = scalene
PYTHON = python3
PYTHON_SOURCES = scalene/[a-z]*.py
C_SOURCES = src/source/get_line_atomic.cpp src/include/*.h* # src/source/libscalene.cpp
CXXFLAGS = /Ox /DNDEBUG /std:c++14 /Zi
CXX = cl
MAIN_INCLUDES = -Isrc -Isrc/include
INCLUDES = $(MAIN_INCLUDES) -Ivendor/Heap-Layers -Ivendor/Heap-Layers/wrappers -Ivendor/Heap-Layers/utility -Ivendor/printf
LIBFILE = lib$(LIBNAME).dll
WRAPPER = # vendor/Heap-Layers/wrappers/gnuwrapper.cpp
SRC = src/source/lib$(LIBNAME).cpp $(WRAPPER) vendor/printf/printf.cpp
all: # vendor-deps $(SRC) $(OTHER_DEPS)
# $(CXX) $(CXXFLAGS) $(INCLUDES) $(SRC) /o $(LIBFILE)
mypy:
-mypy $(PYTHON_SOURCES)
format: black isort clang-format
clang-format:
-clang-format -i $(C_SOURCES) --style=google
isort:
-isort $(PYTHON_SOURCES)
black:
-black -l 79 $(PYTHON_SOURCES)
vendor/Heap-Layers:
cd vendor && git clone https://github.com/emeryberger/Heap-Layers
vendor/printf/printf.cpp:
cd vendor && git clone https://github.com/mpaland/printf
cd vendor\printf && copy printf.c printf.cpp
vendor-deps: clear-vendor-dirs vendor/Heap-Layers vendor/printf/printf.cpp
clear-vendor-dirs:
if exist vendor\ (rmdir /Q /S vendor)
mkdir vendor
pkg: vendor/Heap-Layers vendor/printf/printf.cpp
-rm -rf dist build *egg-info
$(PYTHON) setup.py sdist bdist_wheel
upload: pkg # to pypi
$(PYTHON) -m twine upload dist/*
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1706461831.1513906
scalene-1.5.34/PKG-INFO 0000644 0000765 0000024 00000054766 14555505207 013601 0 ustar 00runner staff Metadata-Version: 2.1
Name: scalene
Version: 1.5.34
Summary: Scalene: A high-resolution, low-overhead CPU, GPU, and memory profiler for Python with AI-powered optimization suggestions
Home-page: https://github.com/plasma-umass/scalene
Author: Emery Berger
Author-email: emery@cs.umass.edu
License: Apache License 2.0
Keywords: performance memory profiler
Classifier: Development Status :: 5 - Production/Stable
Classifier: Framework :: IPython
Classifier: Framework :: Jupyter
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Software Development
Classifier: Topic :: Software Development :: Debuggers
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: Microsoft :: Windows
Requires-Python: >=3.8,!=3.11.0
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: wheel>=0.36.1
Requires-Dist: rich>=10.7.0
Requires-Dist: cloudpickle>=2.2.1
Requires-Dist: pynvml<11.5,>=11.0.0
Requires-Dist: Jinja2>=3.0.3
Requires-Dist: psutil>=5.9.2

# Scalene: a Python CPU+GPU+memory profiler with AI-powered optimization proposals
by [Emery Berger](https://emeryberger.com), [Sam Stern](https://samstern.me/), and [Juan Altmayer Pizzorno](https://github.com/jaltmayerpizzorno).
[](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)
[](https://pypi.org/project/scalene/)[](https://anaconda.org/conda-forge/scalene) [](https://pepy.tech/project/scalene)[](https://anaconda.org/conda-forge/scalene) [](https://pepy.tech/project/scalene) [](https://marketplace.visualstudio.com/items?itemName=EmeryBerger.scalene) 

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

***Scalene web-based user interface:*** [http://plasma-umass.org/scalene-gui/](http://plasma-umass.org/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**
>
> To enable AI-powered optimization suggestions, you need to enter an [OpenAI key](https://openai.com/api/) in the box under "Advanced options". _Your account will need to have a positive balance for this to work_ (check your balance at https://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 Start
#### Installing Scalene:
```console
python3 -m pip install -U scalene
```
or
```console
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.
Commonly used command-line options:
```console
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:
```Python
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:
```Python
# 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)](http://plasma-umass.org/scalene-gui/).
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.
[](https://raw.githubusercontent.com/plasma-umass/scalene/master/docs/scalene-gui-example-full.png)
## Scalene Overview
### Scalene talk (PyCon US 2021)
[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!
[](https://youtu.be/5iEf-_7mM1k "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.

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

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

* **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.
```console
scalene test/testme.py
```
Click to see all Scalene's options (available by running with --help
)
```console
% 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](https://nbviewer.jupyter.org/github/plasma-umass/scalene/blob/master/docs/scalene-demo.ipynb) illustrates the use of Scalene in Jupyter.
Installation:
```console
!pip install scalene
%load_ext scalene
```
Line mode:
```console
%scrun [options] statement
```
Cell mode:
```console
%%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](https://docs.microsoft.com/en-us/windows/wsl/wsl2-index)) and (with limitations) Windows platforms.
> **Note**
>
> The Windows version currently only supports CPU and GPU profiling, but not memory or copy profiling.
>
You can install it as follows:
```console
% pip install -U scalene
```
or
```console
% 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:
```console
% sudo apt install git python3-all-dev
```
Using conda
(Mac OS X, Linux, Windows, and WSL2)
```console
% conda install -c conda-forge scalene
```
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.
> **Note**
>
> The Windows version currently only supports CPU and GPU profiling, but not memory or copy profiling.
>
On ArchLinux
You can install Scalene on Arch Linux via the [AUR
package](https://aur.archlinux.org/packages/python-scalene-git/). 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 `). Use the options `--cli`, `--html`, and `--outfile ` 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 https://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 Information
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.)
To cite Scalene in an academic paper, please use the following:
```latex
@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 Stories
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)!
# Acknowledgements
Logo created by [Sophia Berger](https://www.linkedin.com/in/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.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/Pipfile 0000644 0000765 0000024 00000000325 14555505126 013775 0 ustar 00runner staff [[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
numpy = "*"
pyperf = "*"
pytest = "*"
wheel = "*"
[packages]
cloudpickle = "*"
nvidia-ml-py = "*"
rich = "*"
wheel = "*"
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/Pipfile.lock 0000644 0000765 0000024 00000020507 14555505126 014730 0 ustar 00runner staff {
"_meta": {
"hash": {
"sha256": "1b3352dc4c084bab46f08dbb4d89f16a3665912992c7d7e45e8b9f8a2d204e74"
},
"pipfile-spec": 6,
"requires": {},
"sources": [
{
"name": "pypi",
"url": "https://pypi.org/simple",
"verify_ssl": true
}
]
},
"default": {
"cloudpickle": {
"hashes": [
"sha256:61f594d1f4c295fa5cd9014ceb3a1fc4a70b0de1164b94fbc2d854ccba056f9f",
"sha256:d89684b8de9e34a2a43b3460fbca07d09d6e25ce858df4d5a44240403b6178f5"
],
"index": "pypi",
"version": "==2.2.1"
},
"markdown-it-py": {
"hashes": [
"sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1",
"sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb"
],
"markers": "python_version >= '3.8'",
"version": "==3.0.0"
},
"mdurl": {
"hashes": [
"sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8",
"sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba"
],
"markers": "python_version >= '3.7'",
"version": "==0.1.2"
},
"nvidia-ml-py": {
"hashes": [
"sha256:8d81e5ed993c84006454102af84c4bffdf72ba5c51212b6c0121c65688983e14",
"sha256:ae246ec810a05438375ce345e35171bc3f4a906487e9ea2632473d7e4f4bd375"
],
"index": "pypi",
"version": "==12.535.77"
},
"pygments": {
"hashes": [
"sha256:13fc09fa63bc8d8671a6d247e1eb303c4b343eaee81d861f3404db2935653692",
"sha256:1daff0494820c69bc8941e407aa20f577374ee88364ee10a98fdbe0aece96e29"
],
"markers": "python_version >= '3.7'",
"version": "==2.16.1"
},
"rich": {
"hashes": [
"sha256:146a90b3b6b47cac4a73c12866a499e9817426423f57c5a66949c086191a8808",
"sha256:fb9d6c0a0f643c99eed3875b5377a184132ba9be4d61516a55273d3554d75a39"
],
"index": "pypi",
"version": "==13.5.2"
},
"wheel": {
"hashes": [
"sha256:12b911f083e876e10c595779709f8a88a59f45aacc646492a67fe9ef796c1b47",
"sha256:473219bd4cbedc62cea0cb309089b593e47c15c4a2531015f94e4e3b9a0f6981"
],
"index": "pypi",
"version": "==0.41.1"
}
},
"develop": {
"iniconfig": {
"hashes": [
"sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3",
"sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374"
],
"markers": "python_version >= '3.7'",
"version": "==2.0.0"
},
"numpy": {
"hashes": [
"sha256:0d60fbae8e0019865fc4784745814cff1c421df5afee233db6d88ab4f14655a2",
"sha256:1a1329e26f46230bf77b02cc19e900db9b52f398d6722ca853349a782d4cff55",
"sha256:1b9735c27cea5d995496f46a8b1cd7b408b3f34b6d50459d9ac8fe3a20cc17bf",
"sha256:2792d23d62ec51e50ce4d4b7d73de8f67a2fd3ea710dcbc8563a51a03fb07b01",
"sha256:3e0746410e73384e70d286f93abf2520035250aad8c5714240b0492a7302fdca",
"sha256:4c3abc71e8b6edba80a01a52e66d83c5d14433cbcd26a40c329ec7ed09f37901",
"sha256:5883c06bb92f2e6c8181df7b39971a5fb436288db58b5a1c3967702d4278691d",
"sha256:5c97325a0ba6f9d041feb9390924614b60b99209a71a69c876f71052521d42a4",
"sha256:60e7f0f7f6d0eee8364b9a6304c2845b9c491ac706048c7e8cf47b83123b8dbf",
"sha256:76b4115d42a7dfc5d485d358728cdd8719be33cc5ec6ec08632a5d6fca2ed380",
"sha256:7dc869c0c75988e1c693d0e2d5b26034644399dd929bc049db55395b1379e044",
"sha256:834b386f2b8210dca38c71a6e0f4fd6922f7d3fcff935dbe3a570945acb1b545",
"sha256:8b77775f4b7df768967a7c8b3567e309f617dd5e99aeb886fa14dc1a0791141f",
"sha256:90319e4f002795ccfc9050110bbbaa16c944b1c37c0baeea43c5fb881693ae1f",
"sha256:b79e513d7aac42ae918db3ad1341a015488530d0bb2a6abcbdd10a3a829ccfd3",
"sha256:bb33d5a1cf360304754913a350edda36d5b8c5331a8237268c48f91253c3a364",
"sha256:bec1e7213c7cb00d67093247f8c4db156fd03075f49876957dca4711306d39c9",
"sha256:c5462d19336db4560041517dbb7759c21d181a67cb01b36ca109b2ae37d32418",
"sha256:c5652ea24d33585ea39eb6a6a15dac87a1206a692719ff45d53c5282e66d4a8f",
"sha256:d7806500e4f5bdd04095e849265e55de20d8cc4b661b038957354327f6d9b295",
"sha256:db3ccc4e37a6873045580d413fe79b68e47a681af8db2e046f1dacfa11f86eb3",
"sha256:dfe4a913e29b418d096e696ddd422d8a5d13ffba4ea91f9f60440a3b759b0187",
"sha256:eb942bfb6f84df5ce05dbf4b46673ffed0d3da59f13635ea9b926af3deb76926",
"sha256:f08f2e037bba04e707eebf4bc934f1972a315c883a9e0ebfa8a7756eabf9e357",
"sha256:fd608e19c8d7c55021dffd43bfe5492fab8cc105cc8986f813f8c3c048b38760"
],
"index": "pypi",
"version": "==1.25.2"
},
"packaging": {
"hashes": [
"sha256:994793af429502c4ea2ebf6bf664629d07c1a9fe974af92966e4b8d2df7edc61",
"sha256:a392980d2b6cffa644431898be54b0045151319d1e7ec34f0cfed48767dd334f"
],
"markers": "python_version >= '3.7'",
"version": "==23.1"
},
"pluggy": {
"hashes": [
"sha256:c2fd55a7d7a3863cba1a013e4e2414658b1d07b6bc57b3919e0c63c9abb99849",
"sha256:d12f0c4b579b15f5e054301bb226ee85eeeba08ffec228092f8defbaa3a4c4b3"
],
"markers": "python_version >= '3.7'",
"version": "==1.2.0"
},
"psutil": {
"hashes": [
"sha256:104a5cc0e31baa2bcf67900be36acde157756b9c44017b86b2c049f11957887d",
"sha256:3c6f686f4225553615612f6d9bc21f1c0e305f75d7d8454f9b46e901778e7217",
"sha256:4aef137f3345082a3d3232187aeb4ac4ef959ba3d7c10c33dd73763fbc063da4",
"sha256:5410638e4df39c54d957fc51ce03048acd8e6d60abc0f5107af51e5fb566eb3c",
"sha256:5b9b8cb93f507e8dbaf22af6a2fd0ccbe8244bf30b1baad6b3954e935157ae3f",
"sha256:7a7dd9997128a0d928ed4fb2c2d57e5102bb6089027939f3b722f3a210f9a8da",
"sha256:89518112647f1276b03ca97b65cc7f64ca587b1eb0278383017c2a0dcc26cbe4",
"sha256:8c5f7c5a052d1d567db4ddd231a9d27a74e8e4a9c3f44b1032762bd7b9fdcd42",
"sha256:ab8ed1a1d77c95453db1ae00a3f9c50227ebd955437bcf2a574ba8adbf6a74d5",
"sha256:acf2aef9391710afded549ff602b5887d7a2349831ae4c26be7c807c0a39fac4",
"sha256:b258c0c1c9d145a1d5ceffab1134441c4c5113b2417fafff7315a917a026c3c9",
"sha256:be8929ce4313f9f8146caad4272f6abb8bf99fc6cf59344a3167ecd74f4f203f",
"sha256:c607bb3b57dc779d55e1554846352b4e358c10fff3abf3514a7a6601beebdb30",
"sha256:ea8518d152174e1249c4f2a1c89e3e6065941df2fa13a1ab45327716a23c2b48"
],
"markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'",
"version": "==5.9.5"
},
"pyperf": {
"hashes": [
"sha256:171aea69b8efde61210e512166d8764e7765a9c7678b768052174b01f349f247",
"sha256:9f81bf78335428ddf9845f1388dfb56181e744a69e93d8506697a56dc67b6d5f"
],
"index": "pypi",
"version": "==2.6.1"
},
"pytest": {
"hashes": [
"sha256:78bf16451a2eb8c7a2ea98e32dc119fd2aa758f1d5d66dbf0a59d69a3969df32",
"sha256:b4bf8c45bd59934ed84001ad51e11b4ee40d40a1229d2c79f9c592b0a3f6bd8a"
],
"index": "pypi",
"version": "==7.4.0"
},
"wheel": {
"hashes": [
"sha256:12b911f083e876e10c595779709f8a88a59f45aacc646492a67fe9ef796c1b47",
"sha256:473219bd4cbedc62cea0cb309089b593e47c15c4a2531015f94e4e3b9a0f6981"
],
"index": "pypi",
"version": "==0.41.1"
}
}
}
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/README.md 0000755 0000765 0000024 00000051736 14555505126 013760 0 ustar 00runner staff 
# Scalene: a Python CPU+GPU+memory profiler with AI-powered optimization proposals
by [Emery Berger](https://emeryberger.com), [Sam Stern](https://samstern.me/), and [Juan Altmayer Pizzorno](https://github.com/jaltmayerpizzorno).
[](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)
[](https://pypi.org/project/scalene/)[](https://anaconda.org/conda-forge/scalene) [](https://pepy.tech/project/scalene)[](https://anaconda.org/conda-forge/scalene) [](https://pepy.tech/project/scalene) [](https://marketplace.visualstudio.com/items?itemName=EmeryBerger.scalene) 

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

***Scalene web-based user interface:*** [http://plasma-umass.org/scalene-gui/](http://plasma-umass.org/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**
>
> To enable AI-powered optimization suggestions, you need to enter an [OpenAI key](https://openai.com/api/) in the box under "Advanced options". _Your account will need to have a positive balance for this to work_ (check your balance at https://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 Start
#### Installing Scalene:
```console
python3 -m pip install -U scalene
```
or
```console
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.
Commonly used command-line options:
```console
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:
```Python
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:
```Python
# 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)](http://plasma-umass.org/scalene-gui/).
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.
[](https://raw.githubusercontent.com/plasma-umass/scalene/master/docs/scalene-gui-example-full.png)
## Scalene Overview
### Scalene talk (PyCon US 2021)
[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!
[](https://youtu.be/5iEf-_7mM1k "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.

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

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

* **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.
```console
scalene test/testme.py
```
Click to see all Scalene's options (available by running with --help
)
```console
% 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](https://nbviewer.jupyter.org/github/plasma-umass/scalene/blob/master/docs/scalene-demo.ipynb) illustrates the use of Scalene in Jupyter.
Installation:
```console
!pip install scalene
%load_ext scalene
```
Line mode:
```console
%scrun [options] statement
```
Cell mode:
```console
%%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](https://docs.microsoft.com/en-us/windows/wsl/wsl2-index)) and (with limitations) Windows platforms.
> **Note**
>
> The Windows version currently only supports CPU and GPU profiling, but not memory or copy profiling.
>
You can install it as follows:
```console
% pip install -U scalene
```
or
```console
% 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:
```console
% sudo apt install git python3-all-dev
```
Using conda
(Mac OS X, Linux, Windows, and WSL2)
```console
% conda install -c conda-forge scalene
```
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.
> **Note**
>
> The Windows version currently only supports CPU and GPU profiling, but not memory or copy profiling.
>
On ArchLinux
You can install Scalene on Arch Linux via the [AUR
package](https://aur.archlinux.org/packages/python-scalene-git/). 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 `). Use the options `--cli`, `--html`, and `--outfile ` 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 https://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 Information
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.)
To cite Scalene in an academic paper, please use the following:
```latex
@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 Stories
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)!
# Acknowledgements
Logo created by [Sophia Berger](https://www.linkedin.com/in/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.
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1706461830.8998973
scalene-1.5.34/benchmarks/ 0000755 0000765 0000024 00000000000 14555505207 014577 5 ustar 00runner staff ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/benchmarks/benchmark.py 0000644 0000765 0000024 00000017623 14555505126 017114 0 ustar 00runner staff import os
import sys
import re
import subprocess
import traceback
import statistics
python = "python3"
progname = os.path.join(os.path.dirname(__file__), "julia1_nopil.py")
number_of_runs = 1 # We take the average of this many runs.
# Output timing string from the benchmark.
result_regexp = re.compile("calculate_z_serial_purepython took ([0-9]*\.[0-9]+) seconds")
# Characteristics of the tools.
line_level = {}
cpu_profiler = {}
separate_profiler = {}
memory_profiler = {}
unmodified_code = {}
timing = {}
line_level["baseline"] = None
line_level["cProfile"] = False
line_level["Profile"] = False
line_level["line_profiler"] = True
line_level["pyinstrument"] = False
line_level["yappi_cputime"] = False
line_level["yappi_wallclock"] = False
line_level["pprofile_deterministic"] = True
line_level["pprofile_statistical"] = True
line_level["py_spy"] = True
line_level["memory_profiler"] = True
line_level["scalene_cpu"] = True
line_level["scalene_cpu_memory"] = True
cpu_profiler["baseline"] = None
cpu_profiler["cProfile"] = True
cpu_profiler["Profile"] = True
cpu_profiler["pyinstrument"] = True
cpu_profiler["line_profiler"] = True
cpu_profiler["yappi_cputime"] = True
cpu_profiler["yappi_wallclock"] = True
cpu_profiler["pprofile_deterministic"] = True
cpu_profiler["pprofile_statistical"] = True
cpu_profiler["py_spy"] = True
cpu_profiler["memory_profiler"] = False
cpu_profiler["scalene_cpu"] = True
cpu_profiler["scalene_cpu_memory"] = True
separate_profiler["baseline"] = None
separate_profiler["cProfile"] = False
separate_profiler["Profile"] = False
separate_profiler["pyinstrument"] = False
separate_profiler["line_profiler"] = False
separate_profiler["yappi_cputime"] = False
separate_profiler["yappi_wallclock"] = False
separate_profiler["pprofile_deterministic"] = False
separate_profiler["pprofile_statistical"] = False
separate_profiler["py_spy"] = False
separate_profiler["memory_profiler"] = False
separate_profiler["scalene_cpu"] = True
separate_profiler["scalene_cpu_memory"] = True
memory_profiler["baseline"] = None
memory_profiler["cProfile"] = False
memory_profiler["Profile"] = False
memory_profiler["pyinstrument"] = False
memory_profiler["line_profiler"] = False
memory_profiler["yappi_cputime"] = False
memory_profiler["yappi_wallclock"] = False
memory_profiler["pprofile_deterministic"] = False
memory_profiler["pprofile_statistical"] = False
memory_profiler["py_spy"] = False
memory_profiler["memory_profiler"] = True
memory_profiler["scalene_cpu"] = False
memory_profiler["scalene_cpu_memory"] = True
unmodified_code["baseline"] = None
unmodified_code["cProfile"] = True
unmodified_code["Profile"] = True
unmodified_code["pyinstrument"] = True
unmodified_code["line_profiler"] = False
unmodified_code["yappi_cputime"] = True
unmodified_code["yappi_wallclock"] = True
unmodified_code["pprofile_deterministic"] = True
unmodified_code["pprofile_statistical"] = True
unmodified_code["py_spy"] = True
unmodified_code["memory_profiler"] = False
unmodified_code["scalene_cpu"] = True
unmodified_code["scalene_cpu_memory"] = True
# how the profilers measure time
# - wall clock only
# - virtual (process) time only
# - either one
WallClock = 1
VirtualTime = 2
Either = 3
timing["baseline"] = None
timing["cProfile"] = WallClock
timing["Profile"] = VirtualTime
timing["pyinstrument"] = WallClock
timing["line_profiler"] = WallClock
timing["yappi_cputime"] = Either
timing["yappi_wallclock"] = Either
timing["pprofile_deterministic"] = WallClock
timing["pprofile_statistical"] = WallClock
timing["py_spy"] = Either
timing["memory_profiler"] = None
timing["scalene_cpu"] = Either
timing["scalene_cpu_memory"] = Either
# Command lines for the various tools.
baseline = f"{python} {progname}"
cprofile = f"{python} -m cProfile {progname}"
profile = f"{python} -m profile {progname}"
pyinstrument = f"pyinstrument {progname}"
line_profiler = f"{python} -m kernprof -l -v {progname}"
pprofile_deterministic = f"pprofile {progname}"
pprofile_statistical = f"pprofile --statistic 0.001 {progname}" # Same as Scalene
yappi_cputime = f"yappi {progname}"
yappi_wallclock = f"yappi -c wall {progname}"
py_spy = f"py-spy record -f raw -o foo.txt -- python3.7 {progname}"
scalene_cpu = f"{python} -m scalene {progname}"
scalene_cpu_memory = f"{python} -m scalene {progname}" # see below for environment variables
benchmarks = [(baseline, "baseline", "_original program_"), (cprofile, "cProfile", "`cProfile`"), (profile, "Profile", "`Profile`"), (pyinstrument, "pyinstrument", "`pyinstrument`"), (line_profiler, "line_profiler", "`line_profiler`"), (pprofile_deterministic, "pprofile_deterministic", "`pprofile` _(deterministic)_"), (pprofile_statistical, "pprofile_statistical", "`pprofile` _(statistical)_"), (yappi_cputime, "yappi_cputime", "`yappi` _(CPU)_"), (yappi_wallclock, "yappi_wallclock", "`yappi` _(wallclock)_"), (scalene_cpu, "scalene_cpu", "`scalene` _(CPU only)_"), (scalene_cpu_memory, "scalene_cpu_memory", "`scalene` _(CPU + memory)_")]
# benchmarks = [(baseline, "baseline", "_original program_"), (pprofile_deterministic, "`pprofile` _(deterministic)_")]
# benchmarks = [(baseline, "baseline", "_original program_"), (pprofile_statistical, "pprofile_statistical", "`pprofile` _(statistical)_")]
benchmarks = [(baseline, "baseline", "_original program_"), (py_spy, "py_spy", "`py-spy`"), (scalene_cpu, "scalene_cpu", "`scalene` _(CPU only)_"), (scalene_cpu_memory, "scalene_cpu_memory", "`scalene` _(CPU + memory)_")]
average_time = {}
check = ":heavy_check_mark:"
print("| | Time | Slowdown | Line-level? | CPU? | Python vs. C? | Memory? | Unmodified code? |")
print("| :--- | ---: | ---: | :---: | :---: | :---: | :---: | :---: |")
for bench in benchmarks:
print(bench)
times = []
for i in range(0, number_of_runs):
my_env = os.environ.copy()
if bench[1] == "scalene_cpu_memory":
my_env["PYTHONMALLOC"] = "malloc"
if sys.platform == 'darwin':
my_env["DYLD_INSERT_LIBRARIES"] = "./libscalene.dylib"
if sys.platform == 'linux':
my_env["LD_PRELOAD"] = "./libscalene.so"
result = subprocess.run(bench[0].split(), env = my_env, stderr = subprocess.STDOUT, stdout = subprocess.PIPE)
output = result.stdout.decode('utf-8')
print(output)
match = result_regexp.search(output)
if match is not None:
times.append(round(100 * float(match.group(1))) / 100.0)
else:
print("failed run")
average_time[bench[1]] = statistics.mean(times) # sum_time / (number_of_runs * 1.0)
print(str(average_time[bench[1]]))
if bench[1] == "baseline":
print(f"| {bench[2]} | {average_time[bench[1]]}s | 1.0x | | | | | |")
print("| | | | | |")
else:
try:
if bench[1].find("scalene") >= 0:
if bench[1].find("scalene_cpu") >= 0:
print("| | | | | |")
print(f"| {bench[2]} | {average_time[bench[1]]}s | **{round(100 * average_time[bench[1]] / average_time['baseline']) / 100}x** | {check if line_level[bench[1]] else 'function-level'} | {check if cpu_profiler[bench[1]] else ''} | {check if separate_profiler[bench[1]] else ''} | {check if memory_profiler[bench[1]] else ''} | {check if unmodified_code[bench[1]] else 'needs `@profile` decorators'} |")
else:
print(f"| {bench[2]} | {average_time[bench[1]]}s | {round(100 * average_time[bench[1]] / average_time['baseline']) / 100}x | {check if line_level[bench[1]] else 'function-level'} | {check if cpu_profiler[bench[1]] else ''} | {check if separate_profiler[bench[1]] else ''} | {check if memory_profiler[bench[1]] else ''} | {check if unmodified_code[bench[1]] else 'needs `@profile` decorators'} |")
except Exception as err:
traceback.print_exc()
print("err = " + str(err))
print("WOOPS")
# print(bench[1] + " = " + str(sum_time / 5.0))
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/benchmarks/julia1_nopil.py 0000644 0000765 0000024 00000005355 14555505126 017547 0 ustar 00runner staff import sys
# Disable the @profile decorator if none has been declared.
try:
# Python 2
import __builtin__ as builtins
except ImportError:
# Python 3
import builtins
try:
builtins.profile
except AttributeError:
# No line profiler, provide a pass-through version
def profile(func): return func
builtins.profile = profile
# Pasted from Chapter 2, High Performance Python - O'Reilly Media;
# minor modifications for Python 3 by Emery Berger
"""Julia set generator without optional PIL-based image drawing"""
import time
# area of complex space to investigate
x1, x2, y1, y2 = -1.8, 1.8, -1.8, 1.8
c_real, c_imag = -0.62772, -.42193
@profile
def calculate_z_serial_purepython(maxiter, zs, cs):
"""Calculate output list using Julia update rule"""
output = [0] * len(zs)
for i in range(len(zs)):
n = 0
z = zs[i]
c = cs[i]
while abs(z) < 2 and n < maxiter:
z = z * z + c
n += 1
output[i] = n
return output
@profile
def calc_pure_python(desired_width, max_iterations):
"""Create a list of complex coordinates (zs) and complex
parameters (cs), build Julia set, and display"""
x_step = (float(x2 - x1) / float(desired_width))
y_step = (float(y1 - y2) / float(desired_width))
x = []
y = []
ycoord = y2
while ycoord > y1:
y.append(ycoord)
ycoord += y_step
xcoord = x1
while xcoord < x2:
x.append(xcoord)
xcoord += x_step
# Build a list of coordinates and the initial condition for each cell.
# Note that our initial condition is a constant and could easily be removed;
# we use it to simulate a real-world scenario with several inputs to
# our function.
zs = []
cs = []
for ycoord in y:
for xcoord in x:
zs.append(complex(xcoord, ycoord))
cs.append(complex(c_real, c_imag))
print("Length of x:", len(x))
print("Total elements:", len(zs))
start_time = time.process_time()
output = calculate_z_serial_purepython(max_iterations, zs, cs)
end_time = time.process_time()
secs = end_time - start_time
sys.stdout.flush()
sys.stderr.flush()
output_str = "calculate_z_serial_purepython took " + str(secs) + " seconds"
print(output_str, file=sys.stderr)
sys.stderr.flush()
# This sum is expected for a 1000^2 grid with 300 iterations.
# It catches minor errors we might introduce when we're
# working on a fixed set of inputs.
### assert sum(output) == 33219980
if __name__ == "__main__":
# Calculate the Julia set using a pure Python solution with
# reasonable defaults for a laptop
calc_pure_python(desired_width=1000, max_iterations=300)
sys.exit(-1) # To force output from py-spy
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/benchmarks/new_benchmark.py 0000644 0000765 0000024 00000011045 14555505126 017755 0 ustar 00runner staff import json
import subprocess
import re
import statistics
from glob import glob
from collections import defaultdict
import sys
cmds = {
# "baseline": ["python3"],
# "scalene": ["python3", "-m", "scalene", "--json", "--outfile", "/dev/null"],
# "scalene-cpu": ["python3", "-m", "scalene", "--json", "--cpu", "--outfile", "/dev/null"],
# "scalene-cpu-gpu": ["python3", "-m", "scalene", "--json", "--cpu", "--gpu", "--outfile", "/dev/null"],
# "scalene-5M": ["python3", "-m", "scalene", "--json", "--outfile", "/dev/null", "--allocation-sampling-window", "5242883"],
# "scalene-10M": ["python3", "-m", "scalene", "--json", "--outfile", "/dev/null", "--allocation-sampling-window", "10485767"],
# "scalene-20M": ["python3", "-m", "scalene", "--json", "--outfile", "/dev/null", "--allocation-sampling-window","20971529"],
# "memray": [
# "python3",
# "-m",
# "memray",
# "run",
# "--trace-python-allocators",
# "-f",
# "-o",
# "/tmp/memray.out",
# ],
# "fil": ["fil-profile", "-o", "/tmp/abc", '--no-browser', "run"],
# "austin_full": ["austin", "-o", "/dev/null", "-f"],
# "austin_cpu": ["austin", "-o", "/dev/null"],
# 'py-spy': ['py-spy', 'record', '-o', '/tmp/profile.svg', '--', 'python3'],
# 'cProfile': ['python3', '-m', 'cProfile', '-o', '/dev/null'],
'yappi_wall': ['python3', '-m', 'yappi', '-o', '/dev/null', '-c', 'wall'],
'yappi_cpu': ['python3', '-m', 'yappi', '-o', '/dev/null', '-c', 'cpu'],
# 'pprofile_det': ['pprofile', '-o', '/dev/null'],
# 'pprofile_stat': ['pprofile', '-o', '/dev/null', '-s', '0.001'],
# 'line_profiler': ['kernprof', '-l', '-o', '/dev/null', '-v'],
# 'profile': ['python3', '-m', 'profile', '-o', '/dev/null']
}
result_regexp = re.compile(r"Time elapsed:\s+([0-9]*\.[0-9]+)")
def main():
out = defaultdict(lambda : {})
for progname in [
# "./test/expensive_benchmarks/bm_mdp.py",
# "./test/expensive_benchmarks/bm_async_tree_io.py none",
# "./test/expensive_benchmarks/bm_async_tree_io.py io",
# "./test/expensive_benchmarks/bm_async_tree_io.py cpu_io_mixed",
# "./test/expensive_benchmarks/bm_async_tree_io.py memoization",
# "./test/expensive_benchmarks/bm_fannukh.py",
# "./test/expensive_benchmarks/bm_pprint.py",
# "./test/expensive_benchmarks/bm_raytrace.py",
# "./test/expensive_benchmarks/bm_sympy.py",
"./test/expensive_benchmarks/bm_docutils.py"
]:
for profile_name, profile_cmd in cmds.items():
times = []
for i in range(5):
print(
f"Running {profile_name} on {progname} using \"{' '.join(profile_cmd + progname.split(' '))}\"...",
end="",
flush=True,
)
result = subprocess.run(
profile_cmd + progname.split(' '),
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE,
)
output = result.stdout.decode("utf-8")
# print(output)
match = result_regexp.search(output)
if match is not None:
print(f"... {match.group(1)}", end=('\n' if profile_name != 'memray' else ''))
times.append(round(100 * float(match.group(1))) / 100.0)
if profile_name == 'memray':
res2 = subprocess.run(
['time',
sys.executable,
'-m',
'memray',
'flamegraph',
'-f',
'/tmp/memray.out'],
capture_output=True,
env={'TIME': 'Time elapsed: %e'}
)
output2 = res2.stderr.decode("utf-8")
match2 = result_regexp.search(output2)
if match2 is not None:
print(f"... {match2.group(1)}")
times[-1] += round(100 * float(match2.group(1))) / 100.0
else:
print("... RUN FAILED")
# exit(1)
else:
print("RUN FAILED")
# exit(1)
out[profile_name][progname] = times
with open('yappi.json', 'w+') as f:
json.dump(dict(out), f)
if __name__ == "__main__":
main()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/benchmarks/pystone.py 0000644 0000765 0000024 00000016424 14555505126 016661 0 ustar 00runner staff #! /usr/bin/env python3
"""
"PYSTONE" Benchmark Program
Version: Python/1.1 (corresponds to C/1.1 plus 2 Pystone fixes)
Author: Reinhold P. Weicker, CACM Vol 27, No 10, 10/84 pg. 1013.
Translated from ADA to C by Rick Richardson.
Every method to preserve ADA-likeness has been used,
at the expense of C-ness.
Translated from C to Python by Guido van Rossum.
Version History:
Version 1.1 corrects two bugs in version 1.0:
First, it leaked memory: in Proc1(), NextRecord ends
up having a pointer to itself. I have corrected this
by zapping NextRecord.PtrComp at the end of Proc1().
Second, Proc3() used the operator != to compare a
record to None. This is rather inefficient and not
true to the intention of the original benchmark (where
a pointer comparison to None is intended; the !=
operator attempts to find a method __cmp__ to do value
comparison of the record). Version 1.1 runs 5-10
percent faster than version 1.0, so benchmark figures
of different versions can't be compared directly.
"""
LOOPS = 500000
import time # from time import clock
__version__ = "1.1"
[Ident1, Ident2, Ident3, Ident4, Ident5] = range(1, 6)
class Record:
def __init__(self, PtrComp = None, Discr = 0, EnumComp = 0,
IntComp = 0, StringComp = 0):
self.PtrComp = PtrComp
self.Discr = Discr
self.EnumComp = EnumComp
self.IntComp = IntComp
self.StringComp = StringComp
def copy(self):
return Record(self.PtrComp, self.Discr, self.EnumComp,
self.IntComp, self.StringComp)
TRUE = 1
FALSE = 0
def main(loops=LOOPS):
benchtime, stones = pystones(loops)
print("Pystone(%s) time for %d passes = %g" % \
(__version__, loops, benchtime))
print("This machine benchmarks at %g pystones/second" % stones)
def pystones(loops=LOOPS):
return Proc0(loops)
IntGlob = 0
BoolGlob = FALSE
Char1Glob = '\0'
Char2Glob = '\0'
Array1Glob = [0]*51
Array2Glob = [x[:] for x in [Array1Glob]*51]
PtrGlb = None
PtrGlbNext = None
def Proc0(loops=LOOPS):
global IntGlob
global BoolGlob
global Char1Glob
global Char2Glob
global Array1Glob
global Array2Glob
global PtrGlb
global PtrGlbNext
starttime = time.perf_counter()
for i in range(loops):
pass
nulltime = time.perf_counter() - starttime
PtrGlbNext = Record()
PtrGlb = Record()
PtrGlb.PtrComp = PtrGlbNext
PtrGlb.Discr = Ident1
PtrGlb.EnumComp = Ident3
PtrGlb.IntComp = 40
PtrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING"
String1Loc = "DHRYSTONE PROGRAM, 1'ST STRING"
Array2Glob[8][7] = 10
starttime = time.perf_counter()
for i in range(loops):
Proc5()
Proc4()
IntLoc1 = 2
IntLoc2 = 3
String2Loc = "DHRYSTONE PROGRAM, 2'ND STRING"
EnumLoc = Ident2
BoolGlob = not Func2(String1Loc, String2Loc)
while IntLoc1 < IntLoc2:
IntLoc3 = 5 * IntLoc1 - IntLoc2
IntLoc3 = Proc7(IntLoc1, IntLoc2)
IntLoc1 = IntLoc1 + 1
Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3)
PtrGlb = Proc1(PtrGlb)
CharIndex = 'A'
while CharIndex <= Char2Glob:
if EnumLoc == Func1(CharIndex, 'C'):
EnumLoc = Proc6(Ident1)
CharIndex = chr(ord(CharIndex)+1)
IntLoc3 = IntLoc2 * IntLoc1
IntLoc2 = IntLoc3 / IntLoc1
IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1
IntLoc1 = Proc2(IntLoc1)
benchtime = time.perf_counter() - starttime - nulltime
if benchtime == 0.0:
loopsPerBenchtime = 0.0
else:
loopsPerBenchtime = (loops / benchtime)
return benchtime, loopsPerBenchtime
def Proc1(PtrParIn):
PtrParIn.PtrComp = NextRecord = PtrGlb.copy()
PtrParIn.IntComp = 5
NextRecord.IntComp = PtrParIn.IntComp
NextRecord.PtrComp = PtrParIn.PtrComp
NextRecord.PtrComp = Proc3(NextRecord.PtrComp)
if NextRecord.Discr == Ident1:
NextRecord.IntComp = 6
NextRecord.EnumComp = Proc6(PtrParIn.EnumComp)
NextRecord.PtrComp = PtrGlb.PtrComp
NextRecord.IntComp = Proc7(NextRecord.IntComp, 10)
else:
PtrParIn = NextRecord.copy()
NextRecord.PtrComp = None
return PtrParIn
def Proc2(IntParIO):
IntLoc = IntParIO + 10
while 1:
if Char1Glob == 'A':
IntLoc = IntLoc - 1
IntParIO = IntLoc - IntGlob
EnumLoc = Ident1
if EnumLoc == Ident1:
break
return IntParIO
def Proc3(PtrParOut):
global IntGlob
if PtrGlb is not None:
PtrParOut = PtrGlb.PtrComp
else:
IntGlob = 100
PtrGlb.IntComp = Proc7(10, IntGlob)
return PtrParOut
def Proc4():
global Char2Glob
BoolLoc = Char1Glob == 'A'
BoolLoc = BoolLoc or BoolGlob
Char2Glob = 'B'
def Proc5():
global Char1Glob
global BoolGlob
Char1Glob = 'A'
BoolGlob = FALSE
def Proc6(EnumParIn):
EnumParOut = EnumParIn
if not Func3(EnumParIn):
EnumParOut = Ident4
if EnumParIn == Ident1:
EnumParOut = Ident1
elif EnumParIn == Ident2:
if IntGlob > 100:
EnumParOut = Ident1
else:
EnumParOut = Ident4
elif EnumParIn == Ident3:
EnumParOut = Ident2
elif EnumParIn == Ident4:
pass
elif EnumParIn == Ident5:
EnumParOut = Ident3
return EnumParOut
def Proc7(IntParI1, IntParI2):
IntLoc = IntParI1 + 2
IntParOut = IntParI2 + IntLoc
return IntParOut
def Proc8(Array1Par, Array2Par, IntParI1, IntParI2):
global IntGlob
IntLoc = IntParI1 + 5
Array1Par[IntLoc] = IntParI2
Array1Par[IntLoc+1] = Array1Par[IntLoc]
Array1Par[IntLoc+30] = IntLoc
for IntIndex in range(IntLoc, IntLoc+2):
Array2Par[IntLoc][IntIndex] = IntLoc
Array2Par[IntLoc][IntLoc-1] = Array2Par[IntLoc][IntLoc-1] + 1
Array2Par[IntLoc+20][IntLoc] = Array1Par[IntLoc]
IntGlob = 5
def Func1(CharPar1, CharPar2):
CharLoc1 = CharPar1
CharLoc2 = CharLoc1
if CharLoc2 != CharPar2:
return Ident1
else:
return Ident2
def Func2(StrParI1, StrParI2):
IntLoc = 1
while IntLoc <= 1:
if Func1(StrParI1[IntLoc], StrParI2[IntLoc+1]) == Ident1:
CharLoc = 'A'
IntLoc = IntLoc + 1
if CharLoc >= 'W' and CharLoc <= 'Z':
IntLoc = 7
if CharLoc == 'X':
return TRUE
else:
if StrParI1 > StrParI2:
IntLoc = IntLoc + 7
return TRUE
else:
return FALSE
def Func3(EnumParIn):
EnumLoc = EnumParIn
if EnumLoc == Ident3: return TRUE
return FALSE
if __name__ == '__main__':
import sys
def error(msg):
print(msg, end=' ', file=sys.stderr)
print("usage: %s [number_of_loops]" % sys.argv[0], file=sys.stderr)
sys.exit(100)
nargs = len(sys.argv) - 1
if nargs > 1:
error("%d arguments are too many;" % nargs)
elif nargs == 1:
try: loops = int(sys.argv[1])
except ValueError:
error("Invalid argument %r;" % sys.argv[1])
else:
loops = LOOPS
main(loops)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1706461830.9142976
scalene-1.5.34/docs/ 0000755 0000765 0000024 00000000000 14555505207 013412 5 ustar 00runner staff ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1706461782.0
scalene-1.5.34/docs/Ozsvald-tweet.png 0000644 0000765 0000024 00000272460 14555505126 016703 0 ustar 00runner staff ‰PNG
IHDR @ × òfîä niCCPICC Profile H‰•WXSÉž[’ÐH ½ "5€”Z éE°’@B‰1!¨ØË¢‚k°¡«"ŠmÄbWÅÞ*ʺ¨‹
•7!]÷•ïï›{ÿœ9óŸrgrï@óW"ÉEµ ÈçKãÂcSÓ¤§ d@–`$—'“°bc£ ”ÁûßåÝ
€(îW\ÿœÿ¯¢ÃÈx ã!ÎàËxy7€Wò$Ò| ˆ
½åÔ|‰Ï…XW
„xg)ñNÎPâ£6‰ñlˆ/ Får¥Y h܃zF/òh|†ØẺб?OÈåC¬ˆ}D^Þd.ƒØÚK †ñ fÆwœYãÏâçr³†°2¯QÉ$¹Üéÿgiþ·äåÊ}ØÀAJÃãùÃÞÊ™©ÀTˆ»ÅÑ1ŠZCüAÄWÖ ”"”‡')íQcžŒ
ëô!vásƒ#!6†8Tœ¥ÒgdŠB9ÃÝ‚Nås!6€x±@’ ²Ù,¯ò…ÖeJÙ,•þW:àWáë<'‰¥â#pTü˜F¡01b
ÄV¢ähˆ5 v–å$DªlF
Ùу6Ry¼"~+ˆãâ° %?V)
WÙçÉóÅ6Eœh>/LWÖ;ÅãÄsÁ.Ĭ¤AllÔ`.|Apˆ2wì¹@œ” âù ÉŠW®Å)’ÜX•=n!È
Sè- v—$¨ÖâÉùps*ùñLI~l¢2N¼0›«Œ_¢ Ñ&ƒl jë®ï†¿”3¡€¤ €“J3¸"e`F¯ ü‘ ȆÖ
Ì
@ÔÒ*¯N s`¶``Ex
qˆ¹ð·|`•xÈ[2x5¢xçÂÁƒñæÂ¡˜ÿ÷úAí7
j¢Tù G†æ %1„L'†íq#Ü÷Å£à5Wœ‰{æñÍžð”ÐNxD¸Nè Üž$š/ý!Ê1 ò‡ªj‘ñ}-pÈéá~2ãú¸pÂÝ¡ ={@-[·¢*Œ¸ÿ–ÁwOCeGv!£äaä@²Ý+54<†Xµþ¾>ÊX3†êÍšùÑ?û»êóá=òGKl1v;‹ÀÎcG±zÀÀš°¬;¦ÀC»ëÉÀîô?OäýÃßà“UTRæRãÒåòY9—/˜–¯8xìÉ’éRQ–0ŸÁ‚oƒ#æ9`¸º¸º x×(ÿ¾ÞÆ
¼CýÖoº¿à×Ôßßä›.¢ €ý^ðøþ¦³c À¹Ã<¹´@©Ãü—Є'͘Â7™ÌÇx_B@ˆ‰ L„Ñá>—‚©`&˜Š@ XÖ‚r° l;Áp Ôƒ£à8.‚Ëà:¸wO'x zÀ;Ї ¡!tÄ1C¬GÄa"þH…Ä#©H:’…ˆ92Y€” «rdRìG#'óH;ryˆt!oO(†RQ]ÔµAG¢L”…F¢‰è4‚¢ÑehZ…îFëÐèEô:Ú¾D{1€©cú˜9æ„116ƒ¥a™˜›c¥XV‹5Âç|ëÀº±8§ãÜ îàp< çáSðÙøR¼ß‰×á§ð«øC¼ÿJ Œ އ0–E˜J("”¶NóÔIxG$õ‰¶D/xS‰ÙÄÄ¥Ä
ĽÄfb;ñ1±—D"’I~¤—”O*"'í&5‘®:IÔÔÕÌÔ\ÕBÕÒÔÄjóÕJÕv©W»¢öL¬E¶&ûcÈ|òtòrò6r#ù¹“ÜGѦØRü(‰”lÊW½L}Ÿú9õ‡ê©:T*›:ž*§.£î 6SoSßÒh4Z -–O[F«¦¤= }Ð k8kp4øs4*4ê4®h¼Ò$kZk²4'jj–jÔ¼¤ÙEÖ²ÑbkqµfkUhÖº©Õ«M×¥£§½T{—öyíç:$¾ÎB:'uÓ1º%MçÑзÑOÓ;u‰º¶ºÝlÝÝ=ºmº=z:zîzÉzÓô*ôŽéuècú6úý\ýåúôoèf2Œ5L0lɰÚaW†½7nh 0(6ØkpÝà“!Ã0Ä0Çp¥a½á}#ÜÈÁ(ÎhªÑF£ÓFÝÃu‡ûç
/~`øcÔØÁ8Þx†ñVãVã^S“0‰Éz““&ݦú¦¦Ù¦kL›v™ÑÍüÍDfkÌšÌ^0ô,F.£ŒqŠÑcnln.7ßbÞfÞgak‘d1ßb¯Å}KŠ%Ó2Óre‹e•™Õ«™V5Vw¬ÉÖLk¡õ:ë³ÖïmlmRlÙÔÛ<·5°åØÚÖØÞ³£ÙØM±«²»fO´gÚçØo°¿ì€:x8*.9¢ŽžŽ"Ç
Ží##¼GˆGT¸éDub98Õ8=tÖwŽržï\ïüj¤ÕÈ´‘+GžùÕÅÃ%×e›ËÝQ:£"FÍÕ8꫃+ϵÂõšÍ-ÔmŽ[ƒÛkwGwûF÷[t1‹5Ùtò´ÉíGI‘¤cŠÏ”µSz¤‘Òí2D6AÖ¯?ê[åvòŸäü*
>LMžzpšö4ñ´ÖéÓ—LVZøË|oFËLó™óf>œÅšµe62;cvËË9çtÎ
›»se^Î¼ßæ»Ì_5ÿ¯)š,œ»ðñOa?ÕiI‹n.ò]´i1¾X´¸m‰Û’õK¾ó‹/”¸””–|^Ê[záçQ?—ýÜ¿,sYÛrÏåWWˆWÜX°rç*íU…«¯³ºn
cMñš¿ÖNZ{¾Ô½tÓ:Ê:ùºŽ²¨²†õVëW¬ÿ\.,¿^T±·Ò¸rIåû
ü
W6n¬Ýd²©dӧ͢ͷ¶„m©«²©*ÝJÜZ°õé¶ämgaþR½Ýh{Éö/;Ä;:vÆï‘uâqˤ–»'Çž¼v*îTÛéÈÓç΄ž9y–u¶éœß¹£ç}ξÀ¼PÑób]«Gë¡ß<~;ÔæÙVwÉëRÃeïËí£Û_ ¸râjðÕ3×8×.^¾Þ~#鯛ãovÜâßz~;÷öë;wúîνG¸W|_ë~éãU¿Ûÿ¾·Ã³ãØÃà‡Ý}Ì{üò‰ìÉçÎ…OiOKŸ™=«~îúühWh×åã^t¾”¼ìë.úCûÊWv¯~ý3ðÏÖž±=¯¥¯ûß,}køvÇ_îµôÆö>x—÷®ï}ñÃ;?2?žý”òéYßÔϤÏe_ì¿4~üz¯?¯¿_•r>08ÐÌL Þì €–
öm”qÊ^p@eÿ:€ÀÂÊ~q@<¨…ßïqÝðëæ&