py-spy
py-spy is a sampling profiler for Python. It can attach to a running process or launch a new one to show where your program spends CPU time without restarting the program or modifying its code.
Installation and Setup
Install from PyPI:
Key Features
- Attaches to running Python processes or launches new ones without modifying code or restarting.
- Provides low-overhead sampling, runs outside the target process, and is suitable for production.
- Offers live views and offline recordings that generate flame graphs and speedscope profiles.
- Supports profiling native extension frames with
--nativeand for following child processes with--subprocesses. - Provides flexible filtering and control including sampling rate, GIL holders only, idle threads, and per thread details.
Usage
Profile a running process and write a flame graph:
$ py-spy record -o profile.svg -p <PID>
Launch a program under the profiler:
$ py-spy record -o profile.svg -- python script.py
Watch hot functions live:
$ py-spy top -p <PID>
$ # Or
$ py-spy top -- python script.py
Related Resources
Tutorial
Profiling in Python: How to Find Performance Bottlenecks
In this tutorial, you'll learn how to profile your Python programs using numerous tools available in the standard library, third-party libraries, as well as a powerful tool foreign to Python. Along the way, you'll learn what profiling is and cover a few related concepts.
For additional information on related topics, take a look at the following resources:
- Profiling Performance in Python (Course)
By Leodanis Pozo Ramos • Updated Dec. 15, 2025