Google Cloud Profiler Python Agent

4.1.0 · active · verified Sat Apr 11

The `google-cloud-profiler` Python agent continuously collects CPU usage and memory-allocation information from Python applications in production. It helps identify resource-intensive parts of the code with low overhead, supporting performance analysis through flame graphs in the Google Cloud console. The library is actively maintained with irregular releases, the latest being v4.1.0, focusing on performance and compatibility with newer Python versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Google Cloud Profiler agent in a Python application. The `googlecloudprofiler.start()` function should be called as early as possible in your application's lifecycle. It requires a `service` name and optionally a `service_version` to categorize profiling data. The `project_id` is often auto-detected in Google Cloud environments but must be explicitly set if running outside GCP.

import googlecloudprofiler
import os

def my_application_code():
    # Simulate some work
    result = 0
    for i in range(1000000):
        result += i
    print(f"Application is running. Result: {result}")

# Profiler initialization should happen as early as possible in your application.
try:
    googlecloudprofiler.start(
        service=os.environ.get('GAE_SERVICE', 'my-python-service'),
        service_version=os.environ.get('GAE_VERSION', '1.0.0'),
        # project_id is automatically detected in most GCP environments.
        # If running outside GCP, uncomment and set your project ID:
        # project_id=os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-project-id'),
        # verbose=3  # Uncomment for debug logging
    )
    print("Cloud Profiler started successfully.")
except (ValueError, NotImplementedError) as exc:
    print(f"Failed to start Cloud Profiler: {exc}")
    # Handle errors gracefully, perhaps by logging and continuing without profiling.

my_application_code()
print("Application finished.")

view raw JSON →