Skip to content

01 - Quickstart measure

The shortest possible CodeGreen example: wrap a one-liner Python workload with codegreen run --repeat 3 --warmup 0 --json and read the mean energy from the parsed JSON.

What you learn

  • The 30-second codegreen run shape for any shell command.
  • The shape of the JSON output (energy_j.mean, duration_s.mean).
  • Why -- is required before python3 -c "...".

Prerequisites

  • pip install codegreen
  • On Linux: sudo codegreen init-sensors once (RAPL permissions).

Source

examples/01_quickstart_measure/main.py

"""01 Quickstart: `codegreen run` a one-liner Python workload.

The shortest possible CodeGreen example. Wraps a trivial CPU burn with
`codegreen run --repeat 3 --warmup 0 --json` and prints the mean energy.
"""
import json
import subprocess
import sys


def main() -> int:
    out = subprocess.run(
        ["codegreen", "run", "--repeat", "3", "--warmup", "0", "--json", "--",
         "python3", "-c", "sum(i*i for i in range(2_000_000))"],
        capture_output=True, text=True, check=True,
    )
    data = json.loads(out.stdout)
    mean_j = data["energy_j"]["mean"]
    dur_s = data["duration_s"]["mean"]
    print(f"OK: quickstart_measure; mean_energy_j={mean_j:.4f}; mean_duration_s={dur_s:.4f}")
    return 0


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

Run

python examples/01_quickstart_measure/main.py

Expected output

OK: quickstart_measure; mean_energy_j=0.7234; mean_duration_s=0.1421

Why it matters

codegreen run is the zero-instrumentation entry point. No source edits, no JNI, no AST -- it brackets the entire subprocess and reports hardware RAPL energy with N-run statistics. For CI gating, replace the ad-hoc parse with --budget 5.0 to exit non-zero when the mean exceeds the threshold.

See also: CLI reference: run, 02 - Run with repeats.