# How to benchmark CPU versus GPU inference for energy

> Compare CPU and GPU inference energy fairly: fixed prompts, a quality check, steady load levels, RAPL, NVML and wall meters, and a break-even point.

Source: https://greenai.guide/engineering/cpu-vs-gpu-inference/  
Updated: 2026-11-26

## In short

Neither CPUs nor GPUs are greener for inference by default: a GPU does far more work per joule when it is kept busy, but it also draws power while it waits. Benchmark both on your own model, prompts and traffic: fix the workload, check answer quality, measure energy at several steady load levels including idle, and report energy per successful request. The traffic level at which the GPU's extra idle power is paid back is the number that decides.

## Key points

- Compare energy per successful request at your real traffic levels, not peak tokens per second.
- Measure idle power with the model loaded: at low or irregular traffic it can dominate energy per request.
- CPUs are worth testing for small or quantised models, batch size 1 and sparse traffic; GPUs usually win when there is enough traffic to batch.
- NVML reports a GPU energy counter on Volta and newer, but power readings are sampled or averaged, and one study found nvidia-smi sampled only about 25% of runtime on A100 and H100.
- State the boundary (CPU package, DRAM, GPU or the whole node at the wall), software versions and settings with every result.

## When can a CPU beat a GPU on energy?

**A CPU can use less energy per request when the model is small or quantised, requests arrive one at a time or
rarely, and the CPU server is already running for other reasons.** In those conditions a [GPU](/glossary/#gpu)
spends much of its time waiting, and its idle draw is charged to the few requests it serves.

The reasons are mechanical, not a matter of brand:

- **Batch size 1 under-uses an accelerator.** Generating text one token at a time is limited by memory bandwidth
  more than arithmetic. Fernandez and colleagues, measuring LLM inference on NVIDIA A6000, A6000 Ada and A100 GPUs,
  describe decoding as memory-bound with GPU under-utilisation, and found prefill energy flat at short lengths and
  small batches because the accelerator was far from saturated.
- **Idle power does not disappear.** A GPU server draws power for its accelerators, host processor, memory and fans
  whether or not a request is in flight. If traffic is sparse, that idle energy dominates.
- **Quantisation helps CPUs too.** ONNX Runtime documents 8-bit integer quantisation on CPUs and expects better
  gains on x86-64 processors with VNNI instructions and Arm processors with dot-product instructions. It also warns
  that old hardware without such instructions can run quantised models more slowly. llama.cpp's quantize tool
  converts models to lower-precision GGUF files, which shrinks them and can speed up inference, at some accuracy
  cost. See [how to quantise a model](/how-do-i/quantise-a-model/).
- **Small models fit.** Classification, extraction and short-answer models, and
  [small language models](/glossary/#small-language-model), often run within a CPU server's memory and latency
  budget. Try [a smaller model](/how-do-i/choose-a-smaller-ai-model/) before you size hardware.

None of this proves a CPU will win for you. It tells you when the test is worth running.

## When does a GPU win?

**A GPU usually wins once there is enough concurrent traffic to batch requests, and for models too large or too slow
to serve on a CPU within your latency target.** Batching spreads the accelerator's fixed costs over many requests.

- **Batching and continuous batching.** Kwon and colleagues reported that vLLM, with PagedAttention managing the
  [KV cache](/glossary/#kv-cache), served 2 to 4 times the throughput of earlier systems such as FasterTransformer
  and Orca at the same latency. More useful work in the same powered-on time means less energy per request.
- **Optimisations add up.** Fernandez and colleagues found that applying suitable inference optimisations could
  cut total energy by up to 73% from unoptimised baselines, and that the gains depend heavily on workload shape,
  software stack and hardware. Benchmark the GPU with the serving features you would actually use.
- **Large models and long outputs.** Bigger models and long generations multiply the arithmetic per request, which
  is where accelerators are built to be efficient.

The same paper found that naive energy estimates based on [FLOPs](/glossary/#flops) or theoretical GPU utilisation
significantly underestimate real energy use. That is the case for measuring rather than calculating.

## What makes the comparison fair?

**Hold everything constant except the hardware, and compare at matched quality and latency.** A CPU result with
worse answers, or a GPU result at a traffic level you never see, tells you nothing.

1. **Fix the model and its version**, and write down the precision or quantisation format on each platform. If
   the CPU runs a 4-bit build and the GPU runs half precision, you are comparing two models; that can be the right
   question, but say so and check quality on both.
2. **Fix the prompts.** Use a few hundred real, anonymised requests with their natural spread of input lengths, in
   a file under version control.
3. **Fix generation settings**: maximum output tokens, temperature (0 for repeatability), stop sequences and seed.
4. **Check quality on every response.** Give each prompt a pass test (an expected label, a regular expression, a
   schema check) and count only passing answers as successes. A fast wrong answer is not a saving.
5. **Use the same serving interface.** An OpenAI-compatible endpoint on both sides keeps the client identical.
   llama.cpp's server runs F16 and quantised models on CPU and GPU behind such an API, with continuous batching and
   parallel decoding; vLLM provides an HTTP server implementing OpenAI's Completions and Chat APIs on GPUs.
6. **Set a latency target**, such as a 95th-percentile response time, and discard any configuration that misses it.

<!-- figure: The benchmark set-up: a load generator sends a fixed prompt file to an OpenAI-compatible endpoint on a CPU server and on a GPU server, while RAPL, NVML and a wall meter or BMC feed a recorder that also logs latency and quality results. -->

## How should I run the load?

**Warm up, then hold several steady request rates long enough to cover many meter readings, and measure idle as
its own load level.** Real services are rarely at peak, so the low rates matter as much as the high ones.

- **Idle with the model loaded.** Measure for a few minutes with the server up and no traffic. This is the
  number that decides the break-even.
- **Warm-up.** Send a batch of requests before measuring, so caches, compiled kernels and clock speeds settle.
- **Steady load levels.** Send requests at fixed average rates, for example five rates from your quietest hour
  to your busiest, with random (Poisson) arrival times rather than in lockstep. Discard a ramp period at the start
  of each level and measure a window of several minutes.
- **Batch settings.** On a server with continuous batching, the batch size follows concurrency; record the
  server's maximum batch or slot settings (for llama.cpp, the number of parallel slots) and try two or three.
  For offline jobs, also test fixed batch sizes directly; [batching work that can wait](/how-do-i/batch-ai-requests/)
  is often the biggest saving.
- **Repeat.** Run each level at least three times and report the mean and range. llama-bench, llama.cpp's own
  benchmarking tool, repeats each test five times by default and runs warm-up passes, which is a sensible habit.
- **Find the ceiling.** Raise the rate until latency breaks your target or achieved throughput stops tracking the
  offered rate. That is the platform's capacity, and the point beyond which you need a second node.

## How do I measure the energy?

**Read cumulative energy counters at the start and end of each window, and use sampled power only where no counter
exists.** Then check the software meters against a whole-node reading once per platform.

### CPU package and memory: RAPL

Linux exposes Intel's Running Average Power Limit (RAPL) counters through the powercap interface. Each zone
under `/sys/class/powercap/` has a `name`, an `energy_uj` counter in microjoules and a `max_energy_range_uj`, the
range after which the counter wraps round to zero. RAPL gives no instantaneous power value, so you take the
difference between two readings and handle the wrap.

- **Which zones to add up.** Use the `package-N` zones, plus `dram` where it exists. Package already contains the
  `core` and `uncore` subzones, and the Kepler project warns that zones overlap and should not be summed blindly;
  `psys`, where present, overlaps the package.
- **DRAM is often missing.** Kepler's documentation notes that many client CPUs and AMD processors do not expose a
  DRAM domain, and that virtual machines usually expose no RAPL domains at all. On a cloud virtual machine you will
  probably have to estimate; see [how to measure AI energy](/practice/measure-ai-energy/).
- **Permissions.** After the PLATYPUS power side-channel attacks (CVE-2020-8694 and CVE-2020-8695), Linux made
  RAPL readings privileged, so run the meter as root or grant read access deliberately.

### GPU: NVML

NVIDIA's management library, NVML, offers two routes:

- **The energy counter.** `nvmlDeviceGetTotalEnergyConsumption` returns total energy in millijoules since the
  driver was last reloaded, on Volta or newer GPUs. Read it at the start and end of the window. This is the better
  option.
- **Sampled power.** `nvmlDeviceGetPowerUsage` returns milliwatts for the GPU and its associated circuitry. NVIDIA
  documents that on Ampere (except GA100) and newer GPUs it is averaged over one second, while on GA100 and older it
  is instantaneous. Integrating sampled power over short windows is unreliable: Yang and colleagues found that on
  A100 and H100 GPUs `nvidia-smi` sampled only about 25% of the runtime for power, and that correcting against an
  external meter reduced energy measurement error by an average of 35%, and by as much as 65% in some cases.
- **Utilisation is coarse.** NVML's GPU utilisation is the percentage of time in the sample period during which
  one or more kernels was executing, so 100% does not mean the GPU's compute units were fully used.

### The whole node

A GPU server's energy is more than its GPUs. Where you can, measure the node at the wall with a metering power
strip or power analyser, or read the server's baseboard management controller: `ipmitool dcmi power reading`
returns the platform's power readings on servers that support DCMI. BMC readings are coarse, so sample every few
seconds over long windows. MLPerf's inference power rules take the same view: power is measured at the system level
("at the wall") with an analyser supported by SPEC's PTDaemon. The MLPerf Power methodology built on those rules
is described in a paper that analyses 1,841 reproducible measurements from 60 systems, from microwatt devices to
data-centre clusters.

Data-centre overhead such as cooling sits outside even the wall reading; apply [PUE](/glossary/#pue) separately if
it belongs in your boundary.

<!-- figure: Nested measurement boundaries: CPU package and DRAM (RAPL) and GPU (NVML) inside the server at the wall (BMC or meter), inside the data centre (PUE), with a note of which tool sees each layer. -->

## What should I calculate?

**Energy per successful request, energy per output token, idle power, utilisation, latency and cost, at each load
level.** Keep the totals too, so others can recompute.

| Metric | How | Why |
|---|---|---|
| Energy per successful request (J) | Window energy ÷ requests that completed and passed the quality check | The decision metric; failures and wrong answers still cost energy |
| Energy per output token (J) | Window energy ÷ output tokens completed | Compares runs with different answer lengths |
| Idle power (W) | Energy over an idle window ÷ its duration | Drives the break-even |
| Dynamic energy per request (J) | (Window energy − idle power × duration) ÷ successes | Shows what the work itself adds |
| Utilisation (%) | CPU busy share from `/proc/stat`; GPU from NVML | Explains the results; not a substitute for energy |
| Latency (s) | Median and 95th percentile of successful requests | Rules out configurations that miss the target |
| Cost per successful request | Price per node-hour × window hours ÷ successes | Puts energy next to money; add amortised hardware for owned kit |

Energy divided by tokens hides a trap: when one platform produces longer answers, it looks cheaper per token and
dearer per request. Lead with energy per successful request, and use per-token figures as a cross-check.

## Where is the break-even?

**The GPU pays back its extra idle power above a certain traffic level; below it, the CPU uses less energy per
request.** You find that level from your measurements, not from a datasheet.

At a steady rate of λ requests per second, below each platform's capacity, mean power is roughly:

> P(λ) = P<sub>idle</sub> + λ × e(λ)

where P<sub>idle</sub> is idle power with the model loaded and e(λ) is the extra energy per request at that rate.
Energy per request is then P<sub>idle</sub> ÷ λ + e(λ): the idle term shrinks as traffic grows. The GPU option uses
less energy per request when:

> λ > (P<sub>idle, GPU</sub> − P<sub>idle, CPU</sub>) ÷ (e<sub>CPU</sub> − e<sub>GPU</sub>)

Three things complicate it, which is why you plot measured curves and read the crossing rather than plugging in
one number:

- **e(λ) is not constant.** On a GPU it falls as load rises, because batches get fuller.
- **Capacity steps.** Once traffic exceeds one CPU node's ceiling you need two, and their idle power doubles.
- **Provisioned time is what counts.** If the GPU can be released or scaled to zero when traffic stops, its idle
  term covers only the hours it is actually running. See
  [how to stop GPUs sitting idle](/how-do-i/stop-gpus-sitting-idle/).

Compare like with like: a whole CPU node against a whole GPU node, or the added GPU against nothing, but not a GPU's
own reading against a CPU's whole node. Then compare only points that meet the latency target. If the break-even
sits above your busiest hour, the CPU is the lower-energy choice for this workload; if it sits below your quietest,
the GPU is. In between, look at routing quiet-hour traffic to CPUs, or sharing the GPU across services so it stays
busy.

<!-- figure: Energy per successful request against request rate for a CPU node and a GPU node: the GPU curve starts higher at low traffic because of idle power, falls more steeply, and crosses the CPU curve at the break-even rate; the CPU curve ends at its capacity limit. -->

## What goes in the report?

**Enough for someone else to repeat the run and get a similar answer.** Publish this alongside the numbers:

```yaml
workload:
  model: name, version, licence; precision or quantisation on each platform (e.g. GGUF Q4_K_M, FP16)
  prompts: file name and hash; count; input-token median and range
  generation: max_tokens, temperature, seed, stop sequences
  quality_check: method and pass rate on each platform
hardware:
  cpu_node: CPU model and count, memory, BIOS power profile, OS and kernel
  gpu_node: GPU model and count, driver, CUDA or ROCm version, host CPU and memory
  location: on-premises or cloud instance type and region
software:
  server: name and version (e.g. llama.cpp build, vLLM version), launch flags, batch or slot settings
  benchmark_script: version, client concurrency limit, host it ran on
method:
  load_levels: rates tested, ramp and window length, repeats
  meters: RAPL zones used, NVML counter or sampled power, wall meter or BMC model and interval
  boundary: CPU package + DRAM + GPU, or whole node at the wall; PUE applied or not
results_per_level:
  achieved_rate, successes, errors, quality_failures, energy_J, mean_power_W, idle_W,
  J_per_successful_request, J_per_output_token, latency_p50_s, latency_p95_s,
  cpu_util_pct, gpu_util_pct, cost_per_successful_request
uncertainty:
  mean and range across repeats; meter accuracy if known; software meters checked against the wall: yes/no
```

Leave out embodied carbon only if you say so. Buying a GPU to save operating energy has a manufacturing footprint;
see [accounting for the embodied carbon of AI hardware](/how-do-i/account-for-embodied-carbon-of-ai-hardware/).

## An illustrative benchmark script

**The script below runs the method end to end against any OpenAI-compatible endpoint.** It is an illustration to
adapt, not a finished tool: check it against your own hardware, and against a wall meter, before you trust its
numbers.

It measures idle power, warms up, sends Poisson-timed requests at each rate, and reports one JSON line per load
level and repeat. It reads RAPL package and DRAM zones (polling often enough to catch counter wrap-around), the NVML
energy counter or sampled power, and optionally a whole-node reading from a command such as
`ipmitool dcmi power reading`. Each line of the prompt file is
`{"prompt": "...", "expect": "regular expression"}`.

```python
#!/usr/bin/env python3
"""Illustrative CPU-versus-GPU inference energy benchmark. Adapt it before you rely on it.

Sends a fixed prompt set to an OpenAI-compatible chat endpoint (llama-server, vLLM and
others expose one) at fixed request rates, and reports energy per successful request and
per output token at each rate, next to the idle power of the same machine.

Meters: Linux powercap (RAPL package and DRAM zones), NVIDIA NVML (energy counter, or
sampled power when the counter is not supported) and, optionally, a whole-node reading
from a command such as `ipmitool dcmi power reading`.

Needs: Python 3.9+, httpx; nvidia-ml-py for GPUs. Reading RAPL usually needs root.
"""
import argparse
import asyncio
import glob
import json
import os
import random
import re
import shlex
import statistics
import subprocess
import threading
import time

import httpx

try:
    import pynvml  # provided by the nvidia-ml-py package
except ImportError:
    pynvml = None


class RaplMeter(threading.Thread):
    """Cumulative CPU package and DRAM energy from Linux powercap, in joules.

    A background thread polls the counters often enough to catch every wrap-around.
    """

    def __init__(self, root, interval=1.0):
        super().__init__(daemon=True)
        self.zones, self.interval, self.lock = [], interval, threading.Lock()
        for path in sorted(glob.glob(os.path.join(root, "intel-rapl:*"))):
            with open(os.path.join(path, "name")) as f:
                name = f.read().strip()
            # Package zones already contain core and uncore; psys overlaps the package.
            if name.startswith("package") or name == "dram":
                with open(os.path.join(path, "max_energy_range_uj")) as f:
                    wrap = int(f.read())
                kind = "dram" if name == "dram" else "cpu_package"
                self.zones.append((kind, os.path.join(path, "energy_uj"), wrap))
        self.last = [self._raw(z) for z in self.zones]
        self.totals = [0.0] * len(self.zones)
        if self.zones:
            self.start()

    @staticmethod
    def _raw(zone):
        with open(zone[1]) as f:
            return int(f.read())

    def _poll(self):
        with self.lock:
            for i, zone in enumerate(self.zones):
                now = self._raw(zone)
                delta = now - self.last[i]
                if delta < 0:  # the counter wrapped at max_energy_range_uj
                    delta += zone[2]
                self.totals[i] += delta / 1e6
                self.last[i] = now
            return list(self.totals)

    def run(self):
        while True:
            time.sleep(self.interval)
            self._poll()

    def read(self):
        return self._poll()

    def joules(self, start, end):
        totals = {}
        for (kind, _, _), a, b in zip(self.zones, start, end):
            totals[kind] = totals.get(kind, 0.0) + (b - a)
        return totals


class Sampler(threading.Thread):
    """Calls fn() every interval seconds and keeps (time, value) pairs."""

    def __init__(self, fn, interval):
        super().__init__(daemon=True)
        self.fn, self.interval, self.samples = fn, interval, []
        self._halt = threading.Event()

    def run(self):
        while not self._halt.is_set():
            try:
                value = self.fn()
            except Exception:
                value = None
            if value is not None:
                self.samples.append((time.time(), value))
            self._halt.wait(self.interval)

    def stop(self):
        self._halt.set()

    def window(self, t0, t1):
        return [(t, v) for t, v in self.samples if t0 <= t <= t1]

    def mean(self, t0, t1):
        values = [v for _, v in self.window(t0, t1)]
        return statistics.fmean(values) if values else None

    def integrate(self, t0, t1):
        """Energy in joules over the window from a sampled power series in watts."""
        pts = self.window(t0, t1)
        if len(pts) < 2:
            return None
        area = sum((tb - ta) * (va + vb) / 2 for (ta, va), (tb, vb) in zip(pts, pts[1:]))
        # Scale the mean power of the sampled span to the whole window.
        return area / (pts[-1][0] - pts[0][0]) * (t1 - t0)


class NvmlMeter:
    """GPU energy from NVML: the energy counter (Volta and newer) or sampled power."""

    def __init__(self, interval):
        pynvml.nvmlInit()
        self.handles = [pynvml.nvmlDeviceGetHandleByIndex(i)
                        for i in range(pynvml.nvmlDeviceGetCount())]
        try:
            for h in self.handles:
                pynvml.nvmlDeviceGetTotalEnergyConsumption(h)
            self.has_counter = True
        except pynvml.NVMLError:
            self.has_counter = False
        self.power = Sampler(lambda: sum(pynvml.nvmlDeviceGetPowerUsage(h)
                                         for h in self.handles) / 1000.0, interval)
        self.util = Sampler(lambda: statistics.fmean(pynvml.nvmlDeviceGetUtilizationRates(h).gpu
                                                     for h in self.handles), interval)
        self.power.start()
        self.util.start()

    def read(self):
        if not self.has_counter:
            return None
        return [pynvml.nvmlDeviceGetTotalEnergyConsumption(h) for h in self.handles]  # mJ

    def joules(self, start, end, t0, t1):
        if self.has_counter:
            return sum(b - a for a, b in zip(start, end)) / 1000.0
        return self.power.integrate(t0, t1)  # less accurate: see the sampling caveats


def cpu_util_sampler():
    """Busy share of all CPUs from /proc/stat, as a percentage, between calls."""
    previous = {}

    def sample():
        with open("/proc/stat") as f:
            fields = [int(x) for x in f.readline().split()[1:]]
        idle = fields[3] + fields[4]  # idle + iowait
        total = sum(fields[:8])       # user..steal; guest time is already in user
        if not previous:
            previous.update(idle=idle, total=total)
            return None
        d_total, d_idle = total - previous["total"], idle - previous["idle"]
        previous.update(idle=idle, total=total)
        return 100.0 * (d_total - d_idle) / d_total if d_total else None

    return sample


def node_power_sampler(command):
    """Whole-node watts from a command; the default pattern fits `ipmitool dcmi power reading`."""
    argv = shlex.split(command)
    pattern = re.compile(r"Instantaneous power reading:\s*([\d.]+)\s*Watts|([\d.]+)\s*W\b")

    def sample():
        out = subprocess.run(argv, capture_output=True, text=True, timeout=10).stdout
        m = pattern.search(out)
        return float(m.group(1) or m.group(2)) if m else None

    return sample


async def one_request(client, args, item, records):
    started = time.time()
    record = {"start": started, "ok": False, "quality_ok": False, "out_tokens": 0, "in_tokens": 0}
    try:
        r = await client.post("/v1/chat/completions", json={
            "model": args.model,
            "messages": [{"role": "user", "content": item["prompt"]}],
            "max_tokens": args.max_tokens,
            "temperature": 0,
            "seed": 1,
        })
        r.raise_for_status()
        body = r.json()
        text = body["choices"][0]["message"]["content"] or ""
        usage = body.get("usage") or {}
        record.update(ok=True,
                      quality_ok=bool(re.search(item["expect"], text, re.IGNORECASE)),
                      out_tokens=usage.get("completion_tokens", 0),
                      in_tokens=usage.get("prompt_tokens", 0))
    except (httpx.HTTPError, KeyError, ValueError, IndexError):
        pass
    record["end"] = time.time()
    records.append(record)


async def run_rate(client, args, prompts, rate, meters):
    """Poisson arrivals at `rate` req/s; measure only the steady-state window after the ramp."""
    rapl, nvml, cpu, node = meters
    records, tasks = [], []
    start = time.time()
    t0, t1 = start + args.ramp, start + args.ramp + args.window
    marks = {}

    async def mark(name, at):
        await asyncio.sleep(max(0.0, at - time.time()))
        marks[name] = (time.time(), rapl.read() if rapl else None, nvml.read() if nvml else None)

    markers = [asyncio.create_task(mark("t0", t0)), asyncio.create_task(mark("t1", t1))]
    rng = random.Random(42)
    i = 0
    while time.time() < t1:
        tasks.append(asyncio.create_task(one_request(client, args, prompts[i % len(prompts)], records)))
        i += 1
        await asyncio.sleep(rng.expovariate(rate))
    await asyncio.gather(*markers)
    await asyncio.gather(*tasks)  # drain; requests that finish after t1 are not counted

    (a_t, a_rapl, a_nvml), (b_t, b_rapl, b_nvml) = marks["t0"], marks["t1"]
    seconds = b_t - a_t
    done = [r for r in records if a_t <= r["end"] <= b_t]
    good = [r for r in done if r["ok"] and r["quality_ok"]]
    energy = rapl.joules(a_rapl, b_rapl) if rapl else {}
    if nvml:
        energy["gpu"] = nvml.joules(a_nvml, b_nvml, a_t, b_t)
    if node:
        energy["node"] = node.integrate(a_t, b_t)
    # Boundary: the whole node if metered, otherwise CPU package + DRAM + GPU.
    boundary = "node" if energy.get("node") is not None else "cpu_package+dram+gpu"
    measured = [v for v in energy.values() if v is not None]
    total = energy["node"] if boundary == "node" else (sum(measured) if measured else None)
    out_tokens = sum(r["out_tokens"] for r in done)
    latencies = sorted(r["end"] - r["start"] for r in good)

    def per(x, n):
        return x / n if (x is not None and n) else None

    return {
        "target_rps": rate,
        "achieved_rps": len(done) / seconds,
        "window_s": round(seconds, 2),
        "completed": len(done),
        "errors": sum(1 for r in done if not r["ok"]),
        "quality_failures": sum(1 for r in done if r["ok"] and not r["quality_ok"]),
        "successful": len(good),
        "input_tokens": sum(r["in_tokens"] for r in done),
        "output_tokens": out_tokens,
        "boundary": boundary,
        "energy_j": {k: round(v, 1) for k, v in energy.items() if v is not None},
        "mean_power_w": per(total, seconds),
        "j_per_successful_request": per(total, len(good)),
        "j_per_output_token": per(total, out_tokens),
        "dynamic_j_per_successful_request": (per(total - args.idle_w * seconds, len(good))
                                             if None not in (total, args.idle_w) else None),
        "latency_p50_s": statistics.median(latencies) if latencies else None,
        "latency_p95_s": statistics.quantiles(latencies, n=20)[18] if len(latencies) >= 2 else None,
        "cpu_util_pct": cpu.mean(a_t, b_t),
        "gpu_util_pct": nvml.util.mean(a_t, b_t) if nvml else None,
        "cost_per_successful_request": (per(args.hourly_price * seconds / 3600, len(good))
                                        if args.hourly_price else None),
    }


def measure_idle(args, meters):
    rapl, nvml, cpu, node = meters
    a = (time.time(), rapl.read() if rapl else None, nvml.read() if nvml else None)
    time.sleep(args.idle)
    b = (time.time(), rapl.read() if rapl else None, nvml.read() if nvml else None)
    energy = rapl.joules(a[1], b[1]) if rapl else {}
    if nvml:
        energy["gpu"] = nvml.joules(a[2], b[2], a[0], b[0])
    if node:
        energy["node"] = node.integrate(a[0], b[0])
    seconds = b[0] - a[0]
    watts = {k: v / seconds for k, v in energy.items() if v is not None}
    total = watts["node"] if "node" in watts else sum(watts.values())
    return {"idle_s": round(seconds, 1), "idle_w": watts, "idle_total_w": total if watts else None}


async def main_async(args):
    with open(args.prompts) as f:
        prompts = [json.loads(line) for line in f if line.strip()]
    rapl = RaplMeter(args.rapl_root)
    rapl = rapl if rapl.zones else None
    nvml = None
    if pynvml and not args.no_gpu:
        try:
            nvml = NvmlMeter(args.sample_interval)
        except pynvml.NVMLError:
            print(json.dumps({"warning": "NVML found no usable GPU; measuring CPU only"}))
    cpu = Sampler(cpu_util_sampler(), args.sample_interval)
    cpu.start()
    node = None
    if args.node_power_cmd:
        node = Sampler(node_power_sampler(args.node_power_cmd), args.node_interval)
        node.start()
    meters = (rapl, nvml, cpu, node)
    if not (rapl or nvml or node):
        print(json.dumps({"warning": "no energy meter found; only throughput and latency are reported"}))

    limits = httpx.Limits(max_connections=args.max_in_flight)
    async with httpx.AsyncClient(base_url=args.url, timeout=args.timeout, limits=limits) as client:
        # Model loaded, no traffic: this is the idle power the break-even depends on.
        idle = await asyncio.to_thread(measure_idle, args, meters)
        if args.idle_w is None:
            args.idle_w = idle["idle_total_w"]
        print(json.dumps({"phase": "idle", **idle}))

        warm = []
        for item in prompts[: args.warmup]:
            await one_request(client, args, item, warm)
        print(json.dumps({"phase": "warmup", "requests": len(warm),
                          "quality_pass_rate": per_rate(warm)}))

        for rate in args.rates:
            for repeat in range(args.repeats):
                result = await run_rate(client, args, prompts, rate, meters)
                print(json.dumps({"phase": "load", "repeat": repeat, **result}))


def per_rate(records):
    ok = [r for r in records if r["ok"]]
    return sum(r["quality_ok"] for r in ok) / len(ok) if ok else None


def main():
    p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    p.add_argument("--url", required=True, help="server base URL, e.g. http://127.0.0.1:8080")
    p.add_argument("--model", default="local")
    p.add_argument("--prompts", required=True, help='JSONL lines of {"prompt": ..., "expect": regex}')
    p.add_argument("--rates", type=float, nargs="+", default=[0.2, 0.5, 1, 2, 4])
    p.add_argument("--repeats", type=int, default=3)
    p.add_argument("--max-tokens", type=int, default=256)
    p.add_argument("--warmup", type=int, default=20)
    p.add_argument("--idle", type=float, default=120, help="seconds of idle measurement")
    p.add_argument("--idle-w", type=float, default=None, help="override measured idle watts")
    p.add_argument("--ramp", type=float, default=60, help="seconds before each measured window")
    p.add_argument("--window", type=float, default=300, help="seconds per measured window")
    p.add_argument("--sample-interval", type=float, default=0.1)
    p.add_argument("--node-power-cmd", default=None, help='e.g. "ipmitool dcmi power reading"')
    p.add_argument("--node-interval", type=float, default=2.0)
    p.add_argument("--rapl-root", default="/sys/class/powercap")
    p.add_argument("--no-gpu", action="store_true")
    p.add_argument("--max-in-flight", type=int, default=256)
    p.add_argument("--timeout", type=float, default=120)
    p.add_argument("--hourly-price", type=float, default=None, help="price per node-hour")
    asyncio.run(main_async(p.parse_args()))


if __name__ == "__main__":
    main()
```

Run it once against the CPU server and once against the GPU server, with the same prompt file and rates:

```bash
sudo .venv/bin/python bench_energy.py --url http://127.0.0.1:8080 --prompts prompts.jsonl \
  --rates 0.1 0.25 0.5 1 2 4 --node-power-cmd "ipmitool dcmi power reading" > cpu-node.jsonl
```

Known limits, which you should fix or report:

- **Window edges.** Requests are counted when they finish inside the window, while energy is the window's total.
  At steady state the edges roughly cancel; at very low rates, lengthen the window.
- **The load generator shares the machine** unless you run it elsewhere. Run it from another host so its CPU use
  does not land in the CPU node's figures.
- **The RAPL poll** must run more often than the counter takes to wrap. Check `max_energy_range_uj` against your
  package power.
- **Sampled GPU power** is a fallback only; prefer GPUs with the energy counter.
- **Quality checks** by regular expression suit short answers. For open-ended output, use a stronger check offline
  on the saved responses.

## What to do next

1. Pick one inference workload, save a few hundred anonymised prompts with pass tests, and set a latency target.
2. Run the benchmark script on the CPU servers you already have, with a quantised build of the model, and on one GPU
   configuration with continuous batching switched on.
3. Measure idle power with the model loaded on both, and check the software meters against a wall meter or BMC once.
4. Plot energy per successful request against request rate, mark the latency limit and capacity, and read off the
   break-even.
5. Compare the break-even with your real traffic by hour of day; consider routing quiet hours to CPUs or scaling the
   GPU to zero. See [how to cut the energy of serving a model](/how-do-i/cut-the-energy-of-serving-a-model/).
6. Keep measuring in production with [AI energy observability](/engineering/energy-observability/), and set a
   [baseline](/how-do-i/set-a-baseline-for-ai-energy-savings/) before you change hardware.

## Frequently asked questions

### Is CPU inference more energy-efficient than GPU inference?

Sometimes. For small or quantised models with low or irregular traffic, a CPU server you already run can use less energy per request because it adds no accelerator idle power. With enough traffic to batch requests, a GPU usually does more work per joule. Measure both on your own workload.

### Can I just compare tokens per second?

No. Throughput at peak load says nothing about the hours the hardware spends idle or half-busy, and nothing about answer quality. Compare energy per successful request at the traffic levels you actually see, with latency inside your target.

### How accurate is nvidia-smi for measuring GPU energy?

Treat it with care. NVML has a cumulative energy counter on Volta and newer GPUs, which is better than sampling power. Power readings are averaged over one second on recent GPUs and instantaneous on older ones, and researchers found nvidia-smi sampled only about 25% of runtime on A100 and H100 GPUs. Check against a wall meter once per platform.

### What is RAPL?

Running Average Power Limit: energy counters in many Intel and AMD processors that Linux exposes through the powercap interface in microjoules. They cover the CPU package and, on some machines, DRAM, but not the rest of the server, and usually need root to read.

### Should the benchmark include the whole server?

If you can, yes. A GPU server also runs a host CPU, memory, fans and power supplies. Measure the whole node with a wall meter or the server's management controller, or state clearly that your figures cover components only.

## Sources

- [Power Capping Framework](https://www.kernel.org/doc/html/latest/power/powercap/powercap.html), The Linux kernel documentation (2026)
- [PLATYPUS: software-based power side-channel attacks on x86 (CVE-2020-8694, CVE-2020-8695)](https://platypusattack.com/), Lipp et al. (2020)
- [Kepler metrics (v0.14.0): energy zones and DRAM energy](https://github.com/sustainable-computing-io/kepler/blob/v0.14.0/docs/user/metrics.md), Kepler project, CNCF (2026)
- [NVML API reference: device queries](https://docs.nvidia.com/deploy/nvml-api/api/group__nvmlDeviceQueries.html), NVIDIA (2026)
- [NVML API reference: nvmlUtilization_t](https://docs.nvidia.com/deploy/nvml-api/api/structnvmlUtilization__t.html), NVIDIA (2026)
- [Part-time power measurements: nvidia-smi's lack of attention](https://arxiv.org/abs/2312.02741), Yang et al. (arXiv 2312.02741) (2023)
- [ipmitool manual page (dcmi power reading)](https://github.com/ipmitool/ipmitool/blob/master/doc/ipmitool.1.in), ipmitool project (2023)
- [MLPerf Inference power measurement rules](https://github.com/mlcommons/inference_policies/blob/master/power_measurement.adoc), MLCommons (2022)
- [MLPerf Power: benchmarking the energy efficiency of machine learning systems from microwatts to megawatts for sustainable AI](https://arxiv.org/abs/2410.12032), Tschand et al. (arXiv 2410.12032) (2025)
- [Quantize ONNX models](https://onnxruntime.ai/docs/performance/model-optimizations/quantization.html), ONNX Runtime documentation (2026)
- [llama.cpp HTTP server](https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md), llama.cpp project (2026)
- [llama-bench](https://github.com/ggml-org/llama.cpp/blob/master/tools/llama-bench/README.md), llama.cpp project (2026)
- [llama.cpp quantize tool](https://github.com/ggml-org/llama.cpp/blob/master/tools/quantize/README.md), llama.cpp project (2026)
- [OpenAI-compatible server](https://docs.vllm.ai/en/stable/serving/online_serving/openai_compatible_server/), vLLM documentation (2026)
- [Energy considerations of large language model inference and efficiency optimizations](https://arxiv.org/abs/2504.17674), Fernandez et al. (arXiv 2504.17674) (2025)
- [Efficient memory management for large language model serving with PagedAttention](https://arxiv.org/abs/2309.06180), Kwon et al. (arXiv 2309.06180) (2023)
