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.

Easy Python 3.9+ Aug 9, 2026 Observability & SRE 15 views 0 copies

Python code

25 lines
Python 3.9+
import 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

stdout
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

  1. Add `random.seed(42)` at startup to make the output reproducible.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Observability & SRE

Related tutorials and quizzes for this topic.