菜单
开源

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 基本身份验证。将 <User> 替换为您的 Grafana Cloud 堆栈用户,并将 <Password> 替换为您的 Grafana Cloud API 密钥。

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

Python 性能分析示例

查看以下资源以了解有关 Python 性能分析的更多信息

  • Python 示例演示了如何使用 Pyroscope 分析 Django、Flask 和 FastAPI 应用程序的性能。
  • 在 play.grafana.org 上的 Python 演示