Generate Mock CPU and Memory Metrics in Python
Build a mock_host_metrics() generator that outputs realistic CPU and memory usage percentages for monitoring demos and tests.
Python code
25 linesimport time
import random
def mock_host_metrics():
"""Generate mock CPU and memory metrics for a host."""
cpu_percent = round(random.uniform(10.0, 95.0), 1)
memory_percent = round(random.uniform(20.0, 90.0), 1)
memory_used_mb = round(random.uniform(512, 8192), 1)
return {
"timestamp": int(time.time()),
"cpu_percent": cpu_percent,
"memory_percent": memory_percent,
"memory_used_mb": memory_used_mb,
}
if __name__ == "__main__":
for _ in range(3):
metrics = mock_host_metrics()
print(
f"t={metrics['timestamp']} cpu={metrics['cpu_percent']}% "
f"mem={metrics['memory_percent']}% ({metrics['memory_used_mb']} MB)"
)
Output
t=1710000000 cpu=72.3% mem=54.1% (3841.2 MB)
t=1710000001 cpu=45.8% mem=81.5% (7302.0 MB)
t=1710000002 cpu=90.0% mem=33.2% (1567.8 MB)
How it works
The random.uniform call produces a float in the given range, and round(..., 1) limits it to one decimal place — realistic for percentage metrics. The int(time.time()) captures the current Unix timestamp as a whole number, matching how real monitoring agents report. Returning a dictionary keeps the mock flexible; callers can easily adapt it to JSON payloads or data frames. This function is deterministic in structure but random in values, which is perfect for load-testing dashboards or alert pipelines without needing a real host.
Common mistakes
- Forgetting to seed `random` for reproducible series when writing unit tests
- Returning `time.time()` as float instead of `int` when the schema expects whole seconds
- Hardcoding ranges that never hit edge cases (e.g., 0% or 100%) for alert testing
Variations
- Add `random.seed(42)` at startup to make the output reproducible.
- Use `datetime.now(timezone.utc).isoformat()` instead of a Unix timestamp for ISO‑8601 output.
Real-world use cases
- Feeding mock metrics into a dashboard preview to verify chart rendering without live hosts.
- Simulating load spikes in a test alerting system to validate thresholds and notify logic.
- Generating sample data for a metrics pipeline during a demo or performance benchmark.
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 Prometheus Text Exposition Format in Python easy
- Generate Synthetic CPU Utilization Metrics in Python easy
Keep learning
Related tutorials and quizzes for this topic.