Skip to content

06 - Monitor host

Run codegreen.Monitor (or codegreen monitor) to continuously sample host-wide energy without launching a workload. Useful for already-running daemons (Apache, gunicorn, system services) where you can't embed a Session.

What you learn

  • codegreen.Monitor(interval_ms=...) programmatic form.
  • The shape of each sample: t, joules_total, joules_delta, watts.
  • How to stream samples to a JSONL file for offline analysis.

Prerequisites

  • pip install codegreen
  • A backend (RAPL on Linux, IOReport on macOS, EMI on Windows).

Source

examples/06_monitor_host/main.py

"""06 Host-wide energy monitoring via `codegreen monitor`.

Streams cumulative energy samples for a fixed duration into a JSONL file.
Useful for already-running services or for capturing baseline system load
when no specific PID can be attributed.
"""
import json
import subprocess
import sys
import tempfile
from pathlib import Path


def main() -> int:
    with tempfile.TemporaryDirectory(prefix="cg_monitor_host_") as td:
        out = Path(td) / "energy.jsonl"
        cmd = ["codegreen", "monitor", "-d", "3", "-i", "250", "-o", str(out),
               "--quiet", "--json"]
        p = subprocess.run(cmd, capture_output=True, text=True, check=True)
        summary = json.loads(p.stdout)
        records = [json.loads(ln) for ln in out.read_text().splitlines() if ln]
        sample_lines = sum(1 for r in records if r.get("type") == "sample")
    print(f"OK: monitor_host; duration_s={summary['duration_s']:.2f}; "
          f"total_joules={summary['total_joules']:.3f}; samples={summary['samples']}; "
          f"jsonl_samples={sample_lines}")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Run

python examples/06_monitor_host/main.py

Equivalent CLI

codegreen monitor -d 3 -i 200 -o host.jsonl

Expected output

OK: monitor_host; duration_s=3.00; total_joules=0.453; samples=12; jsonl_samples=12

Why it matters

Continuous monitoring closes the gap between measurement (you wrote the code, you bracket it) and observation (you didn't write the daemon, you still want to know its energy footprint). The Monitor pulls cumulative energy out of the NEMB backend at a fixed interval and computes deltas, so you can plot host power over arbitrary windows.

RAPL is system-wide

Monitor reports the host's total CPU package energy. Two Monitor processes on the same socket will both observe the same Joules -- they don't subtract each other out.

See also: User guide: Continuous Monitoring, 07 - Monitor PID.