Article
performance-profilingapmpythondatadogflame-graphbottleneck-analysiscode-optimization
Profile a Python App with Datadog's Performance Profiler Agent
Install the Datadog Performance Profiler Agent into a Python application. The agent continuously profiles your code, identifying CPU and memory bottlenecks. Use the Datadog UI to analyze flame graphs and pinpoint performance hotspots in your running application.
intermediate30 min5 steps
The play
- Install DependenciesInstall `dd-trace-py`, Datadog's tracing and profiling library for Python, along with Flask to create a sample web application to profile.
- Create a Sample ApplicationCreate a simple Python Flask application with a CPU-intensive endpoint. This gives the Performance Profiler Agent something meaningful to analyze. Save the code provided in the 'Starter' section as `app.py`.
- Run with the Profiler AgentInstead of `python app.py`, use `ddtrace-run`. This command automatically instruments your application. Set environment variables to enable profiling and tag the data with your service name, environment, and version.
- Generate LoadThe profiler collects data when your application is active. Use a simple loop with `curl` in a separate terminal to continuously hit your `/heavy` endpoint and generate performance data.
- Analyze CPU Flame GraphsNavigate to 'APM > Profiling' in your Datadog account. Select your service (`my-profiler-app`). Here you can analyze the CPU flame graph to find which functions consume the most resources. Wider bars represent more time spent.
Starter code
# 1. Save this code as app.py
from flask import Flask
import time
app = Flask(__name__)
# This function simulates a CPU-intensive task
def cpu_intensive_task():
result = 0
for i in range(10_000_000):
result += i
return result
@app.route('/')
def index():
return "Welcome to the profiling demo app!"
@app.route('/heavy')
def heavy_request():
start_time = time.time()
cpu_intensive_task()
end_time = time.time()
duration = end_time - start_time
return f"Heavy task completed in {duration:.2f} seconds."
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001)
# --- How to Run ---
# 2. Install dependencies:
# pip install Flask dd-trace-py
# 3. Run the application with the Datadog profiler enabled.
# (Requires a Datadog Agent running on the host or container)
#
# export DD_SERVICE="my-profiler-app"
# export DD_ENV="development"
# export DD_VERSION="1.0.0"
# export DD_PROFILING_ENABLED="true"
#
# ddtrace-run python app.py
# 4. In a separate terminal, send requests to generate load:
# while true; do curl http://localhost:5001/heavy; echo; sleep 1; done
# 5. Go to your Datadog account: APM > Profiling.
# Select the "my-profiler-app" service to view flame graphs.