Amazon CodeGuru Profiler Python Agent

1.2.6 · active · verified Sat Apr 11

The Amazon CodeGuru Profiler Python Agent is a library that enables profiling of Python applications for Amazon CodeGuru Profiler. It helps analyze application performance, visualize profiling data, and identify performance issues. The library is actively maintained with frequent updates, typically aligning with AWS service updates and Python version support.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize and start the CodeGuru Profiler agent in a Python application. The agent runs in the background, collecting and submitting profiling data to the specified CodeGuru profiling group. Ensure the `CODEGURU_PROFILING_GROUP_NAME` and `AWS_REGION` environment variables are set, or replace the placeholder values, and that the profiling group exists in your AWS account.

import os
import time
from codeguru_profiler_agent import Profiler

# Ensure the profiling group exists in your AWS account and region.
# It's highly recommended to set CODEGURU_PROFILING_GROUP_NAME via an environment variable.
PROFILING_GROUP_NAME = os.environ.get('CODEGURU_PROFILING_GROUP_NAME', 'MyProfilingGroup')
AWS_REGION = os.environ.get('AWS_REGION', 'us-east-1') # Set your target AWS region

def intensive_task():
    """A dummy function to simulate some CPU-bound work."""
    total = 0
    for _ in range(1_000_000):
        total += sum(range(100))
    return total

if __name__ == '__main__':
    print(f"Starting Amazon CodeGuru Profiler agent for group: {PROFILING_GROUP_NAME}")
    print(f"Profiling data will be sent to region: {AWS_REGION}")
    try:
        # Initialize and start the profiler.
        # The agent will automatically submit profiles in the background.
        profiler = Profiler(
            profiling_group_name=PROFILING_GROUP_NAME,
            region_name=AWS_REGION # Specify region if different from default or env var
        )
        profiler.start()
        print("Profiler agent started. Running a simulated intensive task...")
        
        # Simulate your application's main logic
        for i in range(3):
            print(f"Running iteration {i+1}...")
            intensive_task()
            time.sleep(1) # Simulate some work interval
            
        print("Simulated task finished.")

    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        # For long-running applications, the agent typically runs until the process exits.
        # Explicit `profiler.stop()` is generally not required unless you need to
        # stop profiling within a running process before its natural termination.
        print("Application exiting. Profiling data will continue to be submitted as configured.")

view raw JSON →