,

How to Measure a Python Script’s Energy Use

Editorially reviewed and edited by Brett Stadelmann.

To measure a Python script’s energy use, define the workload and measurement boundary, choose a suitable tool and repeat comparable runs. Record energy in Wh or kWh alongside runtime, output correctness and the conditions of the test. Explain which parts of the result come from hardware readings and which are estimates.

A faster script may use less energy, but runtime alone cannot establish that. Power can change during a job, and the tool may cover only some components. A useful comparison needs the same completed task and a clearly stated scope.

This guide gives you a measurement plan, a CodeCarbon integration template and an illustrative reporting example. The numerical results are invented to demonstrate the calculations, not measurements of a particular computer.

Separate power, energy and emissions

Power is a rate, commonly reported in watts. Energy is the amount used over an interval, commonly reported in watt-hours or kilowatt-hours. One kWh equals 1,000 Wh.

For an assumed constant average power, energy in Wh is average watts multiplied by elapsed hours. Real workloads vary, so a measurement method needs to account for the interval rather than treating one instantaneous reading as the whole job.

Operational emissions additionally depend on the electricity’s carbon intensity. The Software Carbon Intensity specification describes operational emissions as energy multiplied by region-specific carbon intensity, with a declared software boundary and functional unit.

Keep the energy result separate from the carbon estimate. A lower reported carbon result could reflect a different emissions factor rather than a more energy-efficient script.

Define what you are comparing

Write down the task in terms someone else could reproduce. Specify the input, required output, algorithm version and relevant configuration. Decide whether the timed interval includes loading data, processing, saving results or the entire workflow.

DecisionExample to record
WorkloadProcess the same 1,000 records and produce equivalent outputs.
BoundaryThe components and interval included by the chosen method.
CorrectnessA check that both versions complete the required task.
ConfigurationHardware, software versions and relevant settings.
Run conditionsBackground activity, cache policy and power settings.
ComparisonRepeated runs of A and B under the same protocol.

If one version omits a step or produces a different result, the comparison no longer answers the original efficiency question. Check equivalence before collecting performance figures.

For possible experiments, see green-code experiments and choose one change at a time.

Understand the measurement boundary

A plug-level meter records electricity for the equipment connected through it. Component counters and software tools may cover CPU, GPU or memory, with different levels of attribution and estimation.

On a laptop, battery charging can complicate a wall-power comparison. On a shared machine, other jobs can contribute to the readings. Record those conditions and choose a setup that matches the question.

CodeCarbon’s methodology focuses on CPU, GPU and RAM and does not separately account for every source such as displays, networking and cooling. Treat its result as a tool-defined compute estimate rather than an automatic full-system footprint.

If your workload relies heavily on remote services, local tracking does not capture all of their computation. Declare the excluded work and use an appropriate method for the remote part.

A CodeCarbon tracking template

CodeCarbon documents a start/stop pattern in its quickstart. Install the package in the environment where you will run the experiment, then adapt the template below. It is an integration template: replace the project import with your own workload.

# Install in the environment used for the experiment:
# python -m pip install codecarbon

from codecarbon import OfflineEmissionsTracker
from your_project import run_workload  # Replace with your own function

tracker = OfflineEmissionsTracker(
    country_iso_code="AUS",  # Replace with the actual compute location
    project_name="version_A",
    measure_power_secs=1,
    tracking_mode="machine",
    output_file="version_A_emissions.csv",
)

tracker.start()
try:
    result = run_workload()
finally:
    emissions_kg = tracker.stop()

print("Estimated operational emissions, kg CO2e:", emissions_kg)

The API reference documents the offline location parameter, sampling interval and output settings. Use the location where the computation runs, which may differ from where you are sitting. Keep the configuration consistent between versions.

A one-second sampling interval here is an example, not a universal optimum. Very short jobs may need a longer representative batch to produce a useful comparison. Faster sampling does not remove model uncertainty or make a tiny difference reliable.

The stop call returns an emissions estimate. Inspect the output record for energy and duration rather than relabelling that return value as energy.

Check how power was obtained

CodeCarbon’s power-estimation documentation describes hardware interfaces and fallback models. Read the logs and record which method your environment actually uses. Two computers can use different underlying methods.

A numerical output does not prove direct measurement of every component. If a fallback model is used, report it as part of the method. Keep the tool version with the results.

Machine-level tracking is easier to interpret on a dedicated machine where your workload dominates the interval. Process attribution on shared hardware remains an approximation, and device-level GPU readings may include other users’ work. Check the current methodology before using shared-environment results.

For an overview of alternatives, green coding tools for beginners explains what different tools can measure.

Run a repeatable comparison

Choose a protocol before looking at the results. Keep the input and output checks fixed, and decide how to handle warm-up, caches, background applications and failed runs.

Alternate or randomise the order of A and B where practical so every B run does not inherit the same position in the sequence. Record the order and conditions. Keep the raw run records.

Repeat enough times to see whether the apparent difference is stable. Five runs in the example below are a teaching choice, not a sufficient sample size for every experiment. A small or variable difference may require more investigation.

Include the tracker consistently for both versions. Measurement itself can add overhead. Explain the chosen method and avoid combining results collected with different boundaries as though they were equivalent.

Worked example: report energy for the same task

Invented data: assume both versions process the same 1,000 records correctly, with the same tool-defined boundary and protocol. The following Wh values illustrate reporting and arithmetic only.

RunVersion A: energy, WhVersion B: energy, Wh
12.42.0
22.51.9
32.32.1
42.42.0
52.42.0

The mean is 2.4 Wh for A and 2.0 Wh for B. The illustrative reduction is (2.4 − 2.0) ÷ 2.4 × 100 = 16.7%. For this batch, that is 0.0024 Wh per record for A and 0.0020 Wh per record for B.

The observed ranges are 2.3–2.5 Wh and 1.9–2.1 Wh. These small invented sets do not establish statistical significance or predict performance on another machine.

A bounded report would say: “Under the stated test conditions, B’s mean reported energy was lower for the same completed batch.” It would then describe the tool, estimation method, repetitions and limitations.

Read units before calculating

CodeCarbon’s output-format reference documents fields including energy_consumed in kWh, duration in seconds and emissions in kg CO₂e. Check the fields and units in the version you use.

Convert deliberately. In the example, 2.4 Wh is 0.0024 kWh. Mixing Wh with a carbon factor expressed per kWh would create a thousandfold error.

Choose a useful unit of work: a completed batch, a successfully processed record or a valid request. If failed work consumes energy, keep it visible in the overall accounting rather than normalising only successful attempts without explanation.

Keep a small experiment record

RecordWhat it should contain
Task and versionsInput, required output and what changed.
EnvironmentMachine, operating system and relevant software versions.
MethodTool, configuration, boundary and measurement or estimation basis.
Raw runsEnergy, runtime, run order, correctness and anomalies.
SummaryTypical result, variation and unit-of-work calculation.
LimitationsExcluded components and conditions affecting interpretation.

Store the script and the report together with a clear input identifier. You should be able to distinguish a genuinely repeated experiment from a reused result.

The energy-efficient coding guide covers how to use measurements to assess a change. Investigate the task and algorithm before assuming a language feature is automatically greener.

What this result does not cover

A component-based operational estimate does not automatically include hardware manufacturing, every supporting service or the full environmental effect of the project. Those require a broader boundary and additional information.

The sustainable computing guide explains that wider context. For remote storage-heavy work, the environmental cost of cloud storage covers additional considerations.

Frequently asked questions

Can I use runtime as a proxy for energy? It can help characterise a workload, but it does not establish energy use on its own. Record both when making an energy-efficiency claim.

Why do runs differ? Background work, caching, thermal behaviour, power settings and estimation methods can affect results. Record conditions and investigate rather than selecting the most favourable run.

What if the script finishes almost instantly? Use a representative repeated batch if that matches your question, and report how it was constructed. Avoid treating a very small estimate as precise.

Can I compare results from different machines? You can study that question, but hardware and measurement differences become part of the experiment. Keep them explicit.

Start with one workload, one boundary and a clear correctness check. A useful measurement is one whose meaning and limitations you can explain.

Featured image: Umberto on Unsplash.