Quick start¶
Get a real energy measurement in three steps. For end-to-end examples (training loops, GPT-2 inference, mode comparison), continue to Python examples. For every parameter and field, see the Python API.
1. Install¶
2. Initialize sensors¶
3. Verify setup¶
If you see energy values (Joules/Watts), sensors are working.
4. Measure your code¶
Three idioms, pick one:
From Python (recommended for libraries / scripts)¶
Bracket the regions you care about with codegreen.Session. Hardware counters are read in-process; no CLI wrapper, no AST instrumentation:
import codegreen
with codegreen.Session("training") as s:
with s.task("data_load"):
load_data()
with s.task("train"):
train()
# writes codegreen_<pid>.json with per-task energy + per-domain breakdown
For all three forms (context manager, explicit start_task/stop_task, decorator) and power-vs-time plots, see Python examples. For every parameter and field, see the Python API.
Whole-script measurement (any command)¶
Wrap an unmodified command. No source changes:
codegreen run python my_script.py --repeat 10 --warmup 1
codegreen run --budget 10.0 --json python train.py # CI energy budget
Per-function auto-instrumentation¶
Inject checkpoints at function boundaries via tree-sitter:
codegreen measure python my_script.py # coarse: main only
codegreen measure python my_script.py -g fine # all functions
codegreen measure python my_script.py -g fine --export-plot energy.html
The HTML plot has a per-function bar chart with hotspot highlighting and a zoomable timeline.
C/C++ programs¶
Java programs¶
How codegreen measure works¶
- Tree-sitter parses the source and locates function boundaries.
- Lightweight checkpoint calls are injected at enter/exit.
- A background C++ thread samples hardware sensors at the configured interval (default 1 ms; see
coordinator.measurement_interval_msinconfig.json, or passsample_interval_ms=NtoSession). - At process exit, checkpoints are correlated with sample timestamps via binary search + linear interpolation.
- Energy between enter/exit = function energy.
Checkpoints are timestamp markers (~100 ns), not synchronous hardware reads (~5-20 us), giving 25-100x lower overhead than traditional profiling.
codegreen.Session skips steps 1-2 entirely: you mark the regions yourself, the same backend reads counters directly.
5. Analyze results¶
Output includes total energy (J), average power (W), per-function breakdown with invocation counts (fine mode), and hotspot highlighting (>90th percentile).
Next steps¶
- Python examples - end-to-end workloads, GPT-2 inference, CLI vs Session comparison
- Python API - every
Sessionparameter, everyTaskResultfield - CLI reference - all commands and options
- Configuration - sampling rate, output paths
- CI/CD integration - continuous energy monitoring