Google Cloud Profiler Python Agent
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
- gotcha The Cloud Profiler API must be enabled for your Google Cloud project, and the service account running your application needs the `roles/cloudprofiler.agent` IAM role. Without these, the agent will fail to upload profiles.
- gotcha The `googlecloudprofiler.start()` function must be called as early as possible in your application's main thread. Calling it too late or from a non-main thread (especially for 'Wall time' profiles) can result in incomplete or missing profiling data.
- gotcha When running applications outside of Google Cloud, you must explicitly provide the `project_id` parameter to `googlecloudprofiler.start()` and configure appropriate authentication credentials (e.g., Application Default Credentials).
- gotcha For applications deployed on Alpine Linux, the Python profiling agent has a native component that requires `build-base` for compilation. Use a multi-stage Docker build to include these dependencies without bloating the final image.
- gotcha When using uWSGI with multiple workers, CPU time and Wall profiles may be incomplete. uWSGI's default behavior can prevent profiling agent initialization in forked worker processes.
- breaking The `google-cloud-profiler` library supports specific Python versions. As of v4.1.0, it officially supports Python 3.7 through 3.11. Using unsupported or end-of-life Python versions may lead to runtime errors or unexpected behavior.
Install
-
pip install google-cloud-profiler
Imports
- googlecloudprofiler
import googlecloudprofiler
Quickstart
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.")