DEV Community

Cover image for I Built a Python Library to Measure Code's Carbon Footprint — Here's What I Learned
Emre
Emre

Posted on • Edited on

I Built a Python Library to Measure Code's Carbon Footprint — Here's What I Learned

You've probably never asked this question while writing code:

"How much CO₂ did this function just emit?"

I hadn't either — until I started building EcoTrace.

The Problem With Existing Tools

CodeCarbon is great for getting started.
But after using it in production, I kept hitting the same walls:

  • No async support — modern Python is async, tracking shouldn't be sync-only
  • System-wide CPU measurement — in a multi-process environment, this is noise
  • No AMD/Intel GPU support — NVIDIA-only in 2025 is a real limitation
  • No side-by-side comparison — I wanted to know: is v1 or v2 of my function greener?

So I built EcoTrace.

How It Works in 5 Lines

from ecotrace import EcoTrace

eco = EcoTrace(region_code="TR")

@eco.track
def train_model():
    # your training code
    pass

train_model()
# [EcoTrace] Duration   : 12.4s
# [EcoTrace] Avg CPU    : 87.3%
# [EcoTrace] CO2 Emitted: 0.00312 gCO2
Enter fullscreen mode Exit fullscreen mode

The Feature That Surprised Me Most

Process-scoped CPU measurement. Most tools measure system-wide CPU —
which means if you're running on a shared server, you're measuring
everyone's compute, not yours.

EcoTrace uses psutil.Process() to track only your process:

# This measures YOUR code, not the entire machine
self._current_process = psutil.Process()
Enter fullscreen mode Exit fullscreen mode

In a Kubernetes pod running 8 services, this difference is enormous.

Async Support — Finally

@eco.track
async def fetch_and_process():
    data = await fetch_from_api()
    return process(data)
Enter fullscreen mode Exit fullscreen mode

Same decorator. Works on sync and async automatically.
EcoTrace detects coroutines at decoration time and routes accordingly.

Comparing Two Implementations

This is my favorite feature:

def bert_inference():
    return model_bert.predict(text)

def distilbert_inference():
    return model_distilbert.predict(text)

result = eco.compare(bert_inference, distilbert_inference)
# BERT:      0.00042 gCO2 | 1.24s
# DistilBERT: 0.00018 gCO2 | 0.51s  ← 57% less carbon
Enter fullscreen mode Exit fullscreen mode

Now you can make architecture decisions based on emissions, not just speed.

40+ Regions, Including Surprising Ones

Sweden (13 gCO₂/kWh) vs Australia (490 gCO₂/kWh) — same code,
37x different carbon footprint depending on where it runs.

This matters for cloud region selection.

Try It

pip install ecotrace
Enter fullscreen mode Exit fullscreen mode

GitHub: github.com/Zwony/ecotrace

I'd love feedback — especially from anyone running async workloads
or multi-GPU setups. What carbon metrics matter most to you?__

Top comments (0)