菜单
开源

Python

Python 性能剖析器与 Pyroscope 集成后,将改变您分析和优化 Python 应用程序的方式。这种结合提供了对 Python 代码库的无与伦比的实时洞察,能够精准识别性能问题。对于专注于提高代码效率和应用速度的 Python 开发者来说,这是一个必不可少的工具。

注意

请参阅可用性能剖析类型,以获取每种语言支持的性能剖析类型列表。

开始之前

要捕获和分析性能剖析数据,您需要一个托管的 Pyroscope OSS 服务器或托管的带有 Grafana Cloud Profiles 的 Pyroscope 实例(需要免费的 Grafana Cloud 账户)。

Pyroscope 服务器可以是用于开发的本地服务器,也可以是用于生产的远程服务器。

向您的应用程序添加 Python 性能剖析

安装 pyroscope-io pip 包

bash
pip install pyroscope-io

配置 Python 客户端

将以下代码添加到您的应用程序中。此代码将初始化 Pyroscope 性能剖析器并开始性能剖析

python
import pyroscope

pyroscope.configure(
  application_name = "my.python.app", # replace this with some name for your application
  server_address   = "http://my-pyroscope-server:4040", # replace this with the address of your Pyroscope server
)

您还可以选择配置其他几个参数

python
import pyroscope

pyroscope.configure(
    application_name    = "my.python.app", # replace this with some name for your application
    server_address      = "http://my-pyroscope-server:4040", # replace this with the address of your Pyroscope server
    sample_rate         = 100, # default is 100
    detect_subprocesses = False, # detect subprocesses started by the main process; default is False
    oncpu               = True, # report cpu time only; default is True
    gil_only            = True, # only include traces for threads that are holding on to the Global Interpreter Lock; default is True
    enable_logging      = True, # does enable logging facility; default is False
    tags                = {
        "region": '{os.getenv("REGION")}',
    }
)

为 Python 应用程序添加性能剖析标签

您可以为代码的特定部分添加标签

python
# You can use a wrapper:
with pyroscope.tag_wrapper({ "controller": "slow_controller_i_want_to_profile" }):
    slow_code()

使用 Python SDK 向 Pyroscope OSS 或 Grafana Cloud Profiles 发送数据

python
import pyroscope

pyroscope.configure(
    application_name = "example.python.app",
    server_address = "<URL>",
    basic_auth_username = '<User>',
    basic_auth_password = '<Password>',
    # Optional Pyroscope tenant ID (only needed if using multi-tenancy). Not needed for Grafana Cloud.
    # tenant_id = "<TenantID>",
)

要配置 Python SDK 向 Pyroscope 发送数据,请将 <URL> 占位符替换为相应的服务器 URL。这可以是 Grafana Cloud URL,也可以是您自己的自定义 Pyroscope 服务器 URL。

如果您需要将数据发送到 Grafana Cloud,则必须配置 HTTP Basic 身份验证。将 <User> 替换为您的 Grafana Cloud Stack 用户,将 <Password> 替换为您的 Grafana Cloud API 密钥。

如果您的 Pyroscope 服务器启用了多租户功能,您需要配置租户 ID。将 <TenantID> 替换为您的 Pyroscope 租户 ID。

Python 性能剖析示例

查阅以下资源,了解有关 Python 性能剖析的更多信息

  • Python 示例,演示如何使用 Pyroscope 对 Django、Flask 和 FastAPI 应用程序进行性能剖析。
  • 一个Python 演示在 play.grafana.org 上。