DEV Community

Emre
Emre

Posted on

I Built a Python Library That Measures Your Code's Carbon Footprint

The Problem

My machine learning scripts run for hours. One day I got curious — how much CO₂ am I actually emitting while training models?

I searched for a simple Python library to measure this. Nothing fit. So I built one.

Introducing EcoTrace

EcoTrace is a lightweight Python library that measures the carbon footprint of your functions using real-time CPU and GPU utilization sampling.

pip install ecotrace
Enter fullscreen mode Exit fullscreen mode

How It Works

from ecotrace import EcoTrace

eco = EcoTrace(region_code="US")

@eco.track
def train_model():
    return sum(i * i for i in range(10**6))

train_model()
# [EcoTrace] Function : train_model
# [EcoTrace] Duration : 0.0452 sec
# [EcoTrace] CO2      : 0.00001823 gCO2
Enter fullscreen mode Exit fullscreen mode

The carbon formula is simple:

energy (Wh) = TDP × cpu_usage% × duration / 3600
CO2 (gCO2)  = (energy / 1000) × carbon_intensity
Enter fullscreen mode Exit fullscreen mode

What Makes It Different

Most tools assume 100% CPU/GPU utilization (full TDP) for the entire duration. EcoTrace uses continuous sampling every 50ms to measure actual utilization — giving you accurate results even for bursty workloads.

Features

  • ✅ Real-time CPU & GPU utilization sampling
  • ✅ 1,800+ CPUs in the database for accurate TDP detection
  • ✅ 36 regions supported with real carbon intensity data
  • ✅ Async function support out of the box
  • ✅ PDF reports with CPU usage charts
  • ✅ Side-by-side comparison of two implementations

GPU Tracking

@eco.track_gpu
def gpu_compute():
    # GPU-intensive work
    pass

# [EcoTrace] GPU Usage : 74.3%
# [EcoTrace] CO2       : 0.00012841 gCO2
Enter fullscreen mode Exit fullscreen mode

Compare Two Implementations

def fast_version():
    return sum(i for i in range(10**5))

def slow_version():
    return sum(i for i in range(10**6))

result = eco.compare(fast_version, slow_version)
Enter fullscreen mode Exit fullscreen mode

Why This Matters

Software is responsible for roughly 2-3% of global CO₂ emissions — similar to the aviation industry. As developers, we rarely think about the environmental cost of our code. EcoTrace makes that cost visible.

Getting Started

pip install ecotrace
Enter fullscreen mode Exit fullscreen mode

GitHub: https://github.com/Zwony/ecotrace

3,000+ downloads in the first week. Would love your feedback! 🌱

Top comments (0)