How to Process System Metrics (RSS, CPU) in Python
Simulate and aggregate RSS and CPU system metrics to compute averages and maximums for monitoring dashboards.
Python code
39 linesimport random
import time
from collections import namedtuple
Metric = namedtuple("Metric", ["name", "value", "unit"])
def generate_metrics(num_metrics: int = 5) -> list:
"""Simulate a batch of system metrics."""
metrics = []
for i in range(num_metrics):
rss = random.randint(50, 500) # MB
cpu = random.uniform(0.0, 100.0) # percent
timestamp = int(time.time())
metrics.append(Metric("rss", rss, "MB"))
metrics.append(Metric("cpu", round(cpu, 2), "%"))
metrics.append(Metric("timestamp", timestamp, "epoch"))
return metrics
def process_metrics(metrics: list) -> dict:
"""Aggregate RSS and CPU metrics."""
rss_values = [m.value for m in metrics if m.name == "rss"]
cpu_values = [m.value for m in metrics if m.name == "cpu"]
return {
"avg_rss_mb": round(sum(rss_values) / len(rss_values), 2),
"max_rss_mb": max(rss_values),
"avg_cpu_pct": round(sum(cpu_values) / len(cpu_values), 2),
"max_cpu_pct": max(cpu_values),
"total_metrics": len(metrics),
}
if __name__ == "__main__":
random.seed(42)
raw = generate_metrics(3)
result = process_metrics(raw)
for key, value in result.items():
print(f"{key}: {value}")
Output
avg_rss_mb: 294.33
max_rss_mb: 465
avg_cpu_pct: 59.39
max_cpu_pct: 95.07
total_metrics: 9
How it works
The code uses a namedtuple to represent each metric with a name, value, and unit, making the data easy to read and filter. generate_metrics creates a list of RSS, CPU, and timestamp metrics in a loop, simulating a batch of system readings. process_metrics filters the metrics by name using list comprehensions and computes the average and maximum values for RSS and CPU. Using round() keeps the aggregated values clean, and the final dictionary is printed key by key for a simple text output.
Common mistakes
- Using `random.randint` for floats, which truncates decimal CPU values; use `random.uniform` instead.
- Dividing by `len(rss_values)` when the list is empty, causing a ZeroDivisionError; add a safety check.
- Forgetting to round CPU percentages, producing long decimals in the output.
- Mixing metric types in one list without a name field, making aggregation messy.
Variations
- Use a dataclass instead of namedtuple for richer metric objects with default values.
- Return metrics as a list of dictionaries instead of namedtuples for easier JSON serialization.
Real-world use cases
- Aggregating CPU and memory usage metrics from a fleet of servers into a monitoring summary.
- Preprocessing time-series metrics from agents to compute averages before sending to a dashboard.
- Simulating system load for testing alerting thresholds in development environments.
Sponsored
More from Observability & SRE
- Adding a Correlation ID to Log Context in Python medium
- Calculate Error Rate from Log Stream in Python easy
- Check if a Timestamp Falls in a Daily Maintenance Window in Python easy
- Export Metrics with OTLP Mock in Python medium
- Generate Mock CPU and Memory Metrics in Python easy
- Generate Prometheus Text Exposition Format in Python easy
Keep learning
Related tutorials and quizzes for this topic.