Skip to main content

EcoTrace: High-precision carbon tracking engine for production Python. Function-level CPU/GPU emission measurement with 50ms continuous sampling, Boavizta TDP database, and audit-ready PDF reporting.

Project description

๐ŸŒฑ EcoTrace โ€” Sustainability OS for Python

The Carbon Intelligence Engine Your Code Deserves

EcoTrace is a high-precision instrumentation engine built for engineers who demand high-fidelity hardware specifications, not generic averages.

Real-time carbon tracking ยท 50+ Global Zones ยท AI-powered hardware insights ยท Zero-config deployment


PyPI - Version Python 3.9+ License: MIT Downloads GitHub stars VS Code Extension Installs


[!TIP] ๐Ÿš€ VS Code User? Monitor your code's carbon footprint in real-time as you write! Download the EcoTrace VS Code extension.



Carbon Aware Live Grid API 50+ Countries 1800+ CPUs Auto Update


Join Discord

๐Ÿ› Report bugs ยท ๐Ÿ’ก Suggest features ยท ๐Ÿ’ป Contribute TDP data ยท ๐Ÿ› ๏ธ Get support

[!IMPORTANT] ๐Ÿ“ข v0.6.0 Out Now: Introducing Live Grid API integration, IP-Based Auto-Detection, and Expanded Global Coverage (50+ Zones). EcoTrace is now officially a Sustainability Operating System.


graph LR
    A["๐Ÿ” Hardware<br/>Auto-Detection"] --> B["โšก EcoTrace<br/>Engine"]
    B --> C["๐ŸŒ Live Grid<br/>API"]
    B --> D["๐Ÿ“Š 50ms<br/>Sampling"]
    C --> E["๐Ÿ“‹ PDF Report<br/>& AI Insights"]
    D --> E
    style A fill:#e1f5fe,stroke:#0288d1,color:#000
    style B fill:#f3e5f5,stroke:#7b1fa2,color:#000
    style C fill:#e8f5e9,stroke:#388e3c,color:#000
    style D fill:#fff3e0,stroke:#f57c00,color:#000
    style E fill:#fce4ec,stroke:#c62828,color:#000

EcoTrace v0.6.0 โ€” Sustainability OS Pipeline


EcoTrace Demo

EcoTrace in Action โ€” Function-level carbon measurement with real-time monitoring


We didn't just build a wrapper; we built a Continuous Measurement Engine. By sampling at 50ms intervals and isolating your process from the OS noise, we provide an audit-ready trace anchored in verified hardware specifications. Because at the end of the day, you can't optimize what you can't measure with precision.


โšก Quick Install

pip install ecotrace

๐Ÿš€ Get Started in 60 Seconds

from ecotrace import EcoTrace

# Initialize โ€” hardware auto-detected, live grid data fetched
eco = EcoTrace(region_code="TR")

# One decorator. Real carbon data. That's it.
@eco.track
def train_model():
    return sum(i * i for i in range(10**6))

train_model()

# Generate audit-ready PDF report
eco.generate_pdf_report("carbon_audit.pdf")
--- EcoTrace v0.6.0 Initialized ---
Region  : TR (482 gCO2/kWh ๐ŸŸข LIVE)
CPU     : 13th Gen Intel Core i7-13700H
Cores   : 20
TDP     : 45.0W
RAM     : 15.6 GB DDR4 @ 3200MHz
GPU     : Intel Iris Xe Graphics
---------------------------------

One decorator. Real carbon data. No configuration files, no background services, no cloud dependencies.


๐Ÿ†• What's New in v0.6.0 โ€” Sustainability OS

EcoTrace v0.6.0 transforms from a measurement tool into a Sustainability Operating System with two game-changing features:

๐ŸŒ Live Grid API Integration

Real-time carbon intensity data from Electricity Maps API replaces static regional constants. Your measurements now reflect the actual grid mix at the moment of execution.

  • 38 country zones with automatic mapping
  • 1-hour intelligent caching (respects API limits)
  • Zero-impact fallback: No API key? No internet? Static data kicks in silently
eco = EcoTrace(
    region_code="TR",
    grid_api_key="YOUR_KEY"
)
# Region: TR (482 gCO2/kWh ๐ŸŸข LIVE)

๐ŸŒฑ Auto-Update System

EcoTrace now checks for updates automatically at startup and asks politely:

[EcoTrace] ๐ŸŒฑ A new version is available! (v0.5.2 โ†’ v0.6.0)
[EcoTrace] Would you like to update? (y/n):
  • Non-blocking: 3-second timeout, never delays your app
  • Interactive: y upgrades via pip, n skips
  • CI/CD safe: Disable with check_updates=False
  • PEP 440 compliant semantic version comparison

๐Ÿ’ก Why EcoTrace?

Modern software teams face increasing pressure to quantify their carbon footprint โ€” from EU CSRD mandates to internal ESG commitments. Most carbon tools bolt on heavy instrumentation that distorts the workloads they measure.

EcoTrace takes a fundamentally different approach.

๐Ÿ”ฌ Scientifically Grounded

TDP-based energy estimation powered by Boavizta's database of 1,800+ CPU models. Every measurement traces back to verified manufacturer specifications โ€” eliminating broad category-level guesswork.

๐Ÿชถ Minimal Overhead

50 ms daemon-thread sampling with process-scoped isolation. Zero interference with your hot paths. Designed for production, not just benchmarks.

๐Ÿ“‹ Compliance-Ready

Per-function gCOโ‚‚ audit trail with timestamped CSV logs and PDF reports. Ready for ESG, GHG Protocol, and EU CSRD documentation.


๐Ÿ†š How EcoTrace Compares

Feature EcoTrace v0.6.0 CodeCarbon CarbonTracker
API Style โœ… One-line @track decorator โœ… Decorator + Context โŒ Manual start/stop
Granularity โœ… Per-function (Micro-workloads) โš ๏ธ Session-level (Macro) โš ๏ธ Epoch-level (ML only)
Live Grid API โœ… Electricity Maps (Zero-config) โœ… ElectricityMaps (Requires token) โŒ Static only
Process Isolation โœ… psutil.Process() (Isolated) โŒ System-wide (Captures OS noise) โŒ System-wide (Captures OS noise)
Continuous Sampling โœ… 50ms daemon threads โš ๏ธ 15s intervals โŒ Point-in-time (Epoch)
AI Insights โœ… Gemini-powered recommendations โŒ โŒ
Crash-Proof โœ… Graceful fallback (Always returns) โŒ Hard crashes / Exceptions โŒ Hard crashes / Exceptions
Auto-Update โœ… Interactive PyPI check โŒ โŒ
Async Support โœ… Auto-detected (asyncio) โŒ โŒ
GPU Support โœ… NVIDIA + AMD + Intel โš ๏ธ NVIDIA only โš ๏ธ NVIDIA only
PDF Reports โœ… Built-in with charts โŒ CSV / External dashboards โŒ Local logs
Function Comparison โœ… eco.compare(f1, f2) โŒ โŒ
CPU TDP Database โœ… 1,800+ models (Boavizta) โš ๏ธ ~1,200 models โŒ Manual config
Zero Config โœ… Full auto-detection โš ๏ธ Config required โš ๏ธ Config required

๐ŸŽฏ Key Differentiators

  • System Noise Filtration (Process Isolation): Tools that rely on system-wide RAPL sensors capture background OS noise (Windows updates, browsers, etc.). EcoTrace isolates down to the exact psutil.Process() and its children, providing a calculated footprint isolated to your code's specific execution.
  • True Function-Level Granularity: CodeCarbon defaults to 15-second tracking intervals, and CarbonTracker measures per heavy ML epoch. EcoTrace's continuous 50ms micro-sampling allows it to accurately track bursty web server requests, async I/O waits, and GIL contention that other tools completely miss.
  • Fail-Safe Architecture: Carbon tools are for observabilityโ€”they should never crash your product. While missing permissions, VMs, or missing hardware drivers cause other trackers to throw fatal execution-halting exceptions, EcoTrace gracefully falls back to static rule-based estimations and guarantees your application keeps running.
  • Actionable AI Assistant: Instead of just outputting a CSV file and leaving you guessing, EcoTrace directly feeds the metrics to Google Gemini. It acts as a Green-Coding Assistant, offering hardware-specific optimization advice (e.g., "Switch this 12-second CPU-bound loop to a vectorized NumPy array to save 15% energy").

๐Ÿ“ฆ Core API

@eco.track โ€” CPU Carbon Measurement

# Synchronous โ€” works out of the box
@eco.track
def train_model():
    pass

# Asynchronous โ€” detected and handled automatically
@eco.track
async def fetch_data():
    await asyncio.sleep(1)
    return await api.get("/data")

Under the hood: A background daemon thread samples process-level CPU utilization every 50 ms, ensuring measurements are scoped to your process โ€” not polluted by system-wide activity.


@eco.track_gpu โ€” GPU-Aware Carbon Measurement

Supports NVIDIA, AMD, and Intel GPUs with real-time utilization sampling:

eco = EcoTrace(region_code="US", gpu_index=0)

@eco.track_gpu
def gpu_inference():
    # CUDA / GPU workload
    pass

# [EcoTrace] GPU Carbon Emissions: 0.00012841 gCO2
# [EcoTrace] Duration     : 1.2400 sec
# [EcoTrace] GPU Usage    : 74.3%

Graceful degradation: No GPU detected? Function executes normally. Drivers missing? A notice is logged. It never crashes your application.


eco.compare() โ€” Side-by-Side Analysis

def bubble_sort(data):
    ...  # O(nยฒ)

def quick_sort(data):
    ...  # O(n log n)

result = eco.compare(bubble_sort, quick_sort)
# [EcoTrace] Comparison Results:
# Function 1: bubble_sort  โ€” 0.3821 sec โ€” 0.00042917 gCO2
# Function 2: quick_sort   โ€” 0.0089 sec โ€” 0.00000998 gCO2

eco.track_block() โ€” Context Manager Tracking

with eco.track_block("data_pipeline"):
    df = load_data()
    df = transform(df)
    save_results(df)

# [EcoTrace] Block 'data_pipeline': 2.341s, 45.2% CPU, 0.000234g CO2

eco.generate_pdf_report() โ€” Audit-Ready Reports

eco.generate_pdf_report("quarterly_carbon_audit.pdf")

Report includes:

  • ๐Ÿ–ฅ๏ธ Hardware profile (CPU model, TDP, cores, GPU, region)
  • ๐Ÿ“Š CPU & GPU usage-over-time charts (matplotlib rendered)
  • ๐Ÿ“‹ Timestamped function-by-function emission history
  • ๐Ÿ†š Side-by-side comparison tables
  • ๐Ÿค– AI-powered optimization insights (with Gemini API key)
  • ๐Ÿ“ˆ Total cumulative COโ‚‚ emissions

๐ŸŒ Live Grid API โ€” Electricity Maps Integration

EcoTrace v0.6.0 fetches real-time carbon intensity from the Electricity Maps API, replacing static constants with live grid data:

graph TD
    A["Cache Check (1-Hour)"] -->|Hit| B["Return Cached Data"]
    A -->|Miss| C["Electricity Maps API Fetch"]
    C -->|Success| D["Update Cache & Return Live Data"]
    C -->|Failure / No Network| E["Constants.json (Static Fallback)"]
    
    style A fill:#f8f9fa,stroke:#ced4da,color:#212529,stroke-width:1px,rx:4px,ry:4px
    style B fill:#e6f4ea,stroke:#ceead6,color:#0d652d,stroke-width:1px,rx:4px,ry:4px
    style C fill:#e8f0fe,stroke:#d2e3fc,color:#1967d2,stroke-width:1px,rx:4px,ry:4px
    style D fill:#e6f4ea,stroke:#ceead6,color:#0d652d,stroke-width:1px,rx:4px,ry:4px
    style E fill:#fce8e6,stroke:#fad2cf,color:#c5221f,stroke-width:1px,rx:4px,ry:4px
# Option 1: Pass key directly
eco = EcoTrace(region_code="DE", grid_api_key="YOUR_KEY")

# Option 2: Environment variable
# export ECOTRACE_GRID_API_KEY="YOUR_KEY"
eco = EcoTrace(region_code="DE")

# Output:
# [EcoTrace] ๐ŸŒ Live grid data: 312 gCO2/kWh
# Region: DE (312 gCO2/kWh ๐ŸŸข LIVE)

No API key? EcoTrace works perfectly with static data. Live grid is an opt-in upgrade for scientific precision.


๐Ÿค– Gemini AI Insights โ€” Green Coding Assistant

EcoTrace integrates Google Gemini AI to transform raw metrics into actionable optimization advice:

eco = EcoTrace(api_key="YOUR_GEMINI_API_KEY")
# Or: export GEMINI_API_KEY="YOUR_KEY"

eco.generate_pdf_report("smart_audit.pdf")

AI-Powered Insights include:

  • Vectorization: "Your i7-13700H supports AVX-512; use NumPy for this loop to save 15% energy."
  • Architecture Tuning: "This function is I/O bound; switching to asyncio could reduce idle CPU carbon by 20%."
  • Library Swaps: "Consider lxml instead of xml.etree for this workload to improve efficiency."

Opt-in Feature: Only activated when a valid GEMINI_API_KEY is provided. No key? EcoTrace operates with full local monitoring and rule-based insights.


๐Ÿ“Š Concrete Evidence: EcoTrace in Action

To demonstrate EcoTrace's low overhead and high precision capabilities across different workload spectrums, we ran both minimal and maximum stress tests, alongside Gemini AI's actionable insights.

๐Ÿƒ 1. Lightweight Workload (Single-Thread Intensive)

We ran a simple, single-threaded mathematical task (lightweight_test_v5.py) to show how EcoTrace gently handles micro-measurements entirely in daemon threads without polluting the main process.

  • Function Name: light_task
  • Execution Time: 2.00 s
  • CPU Utilization: 4.8% (Process-isolated average)
  • Carbon Footprint: 0.000574 gCOโ‚‚

Lightweight Test Graph

๐Ÿ”ฅ 2. Heavyweight Workload (Global Multi-Core Saturation)

We ran the "Beast" stress test (beast_stress_test.py), pushing all 20 cores of an i7-13700H processor to their absolute limits. This proves that the core normalization engine correctly scales usage percentages to 100% capacity and maintains system stability under extreme stress.

  • Function Name: beast_stress_test
  • Execution Time: 14.50 s
  • CPU Utilization: 77.0% (Average sustained global multi-core saturation)
  • Carbon Footprint: 0.414649 gCOโ‚‚

Heavyweight Test Graph

๐Ÿ’ก 3. AI Performance Insights (ร–neriler)

Using the built-in Gemini AI integration, EcoTrace analyzes these metrics and provides actionable green-coding recommendations, dynamically detecting anomalies like single-thread bottlenecks or over-utilized loops.

Performance Insights


๐Ÿ”ฌ The Science Behind EcoTrace

EcoTrace implements a TDP-based energy estimation model, the industry-standard approach for software-level carbon measurement:

Energy (Wh) = TDP (W) ร— CPU Utilization (%) ร— Duration (s) / 3600
Carbon (gCOโ‚‚) = Energy (kWh) ร— Carbon Intensity (gCOโ‚‚/kWh)
Component Source Detail
TDP Boavizta CPU Specs 1,800+ CPU models with manufacturer-reported TDP values
CPU Utilization psutil.Process().cpu_percent() Process-scoped, 50 ms continuous sampling via daemon threads
Duration time.perf_counter() High-resolution monotonic clock, immune to NTP drift
Carbon Intensity Electricity Maps API + IEA 38 countries with live or static grid emission factors

Why 50 ms Continuous Sampling?

Most carbon trackers take a single CPU reading at the start and end. They miss bursty workloads, GIL contention, and I/O waits entirely.

Traditional:  โ”€โ”€โ– โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ– โ”€โ”€  (2 data points)
EcoTrace:     โ”€โ”€โ– โ”€โ”€โ– โ”€โ”€โ– โ”€โ”€โ– โ”€โ”€โ– โ”€โ”€โ– โ”€โ”€โ– โ”€โ”€โ– โ”€โ”€  (N data points @ 50ms)

Result: Significantly more accurate energy estimation, especially for variable CPU profiles.


๐Ÿงช Engineering Excellence & Robustness

EcoTrace is engineered for enterprise-grade production deployment with a focus on precision, safety, and zero-impact monitoring:

Strategy Technical Implementation
Smart Core Normalization Automatically scales multi-core CPU usage (e.g., 800% on 8 cores) down to a normalized 0-100% range for intuitive analysis.
Process Tree Intelligence Uses recursive process tracking to capture carbon/RAM from all child processes in complex multi-processing applications.
Crash-Proof Diagnostics Replaces silent fail blocks with descriptive error logging. If measurement fails, the result is still returned, but the reason is clearly logged.
Idle Baseline Subtraction Conducts a 100ms system baseline measurement to subtract background noise, reporting only your code's incremental carbon footprint.
Universal Async Support Zero-config @track decorator automatically detects and handles asyncio coroutines vs synchronous functions.
GPU Fallback Chain NVIDIA (pynvml) โ†’ AMD/Intel (WMI) โ†’ graceful None. Measurement never crashes your app if drivers are missing.
Thread-Safe Sampling All buffers are protected by threading.Lock and deque(maxlen) to prevent memory leaks and race conditions during high-frequency sampling.

๐Ÿ—บ๏ธ Global Coverage โ€” 50+ Countries

EcoTrace supports 50+ countries with both static carbon intensity values and live Electricity Maps zone mappings:

EcoTrace Global Coverage

Click to expand full region table
Code Country gCOโ‚‚/kWh Code Country gCOโ‚‚/kWh
SE Sweden 13 CH Switzerland 25
NO Norway 26 FR France 55
FI Finland 65 BR Brazil 74
NZ New Zealand 120 CA Canada 130
AT Austria 158 DK Denmark 166
BE Belgium 167 PT Portugal 176
ES Spain 187 HU Hungary 223
IT Italy 233 GB United Kingdom 253
NL Netherlands 290 RO Romania 293
AR Argentina 314 US United States 367
DE Germany 385 NG Nigeria 385
SG Singapore 408 CZ Czech Republic 412
KR South Korea 415 EG Egypt 448
JP Japan 463 TR Turkey 475
AU Australia 490 TH Thailand 513
MX Mexico 527 CN China 555
PH Philippines 558 MY Malaysia 585
PL Poland 635 IN India 708
ID Indonesia 761 ZA South Africa 928
KE Kenya 110 UA Ukraine 150
CO Colombia 155 IE Ireland 275
CL Chile 300 GR Greece 300
AE United Arab Emirates 385 IL Israel 400
TW Taiwan 494 GLOBAL Worldwide Average 475

Static values from IEA 2024 global averages. With Live Grid API enabled, values update in real-time.

Supported Hardware

๐Ÿ–ฅ๏ธ CPU

Vendor Families
Intel Core i3/i5/i7/i9, Xeon, Atom
AMD Ryzen 3/5/7/9, Threadripper, EPYC
Apple M1, M2, M3, M4 series

๐ŸŽฎ GPU

Vendor Method
NVIDIA pynvml (NVML)
AMD WMI (Windows)
Intel WMI (Windows)

๐Ÿง  RAM

Type Watt Factor
DDR4 0.375 W/GB
DDR5 0.285 W/GB
Auto-detected via clock speed

๐Ÿ—บ๏ธ Roadmap

EcoTrace is building toward a complete sustainability intelligence platform:

Version Feature Status
v0.6.0 ๐ŸŒ Live Grid API โ€” Real-time carbon intensity (Electricity Maps) โœ… Released
v0.6.0 ๐ŸŒฑ Auto-Update โ€” Interactive PyPI version check โœ… Released
v0.7.0 ๐Ÿ–ฅ๏ธ VS Code Extension โ€” Live IDE monitoring status bar โœ… Released
v0.6.1 ๐Ÿ›ก๏ธ CI/CD Carbon Gates โ€” GitHub Actions integration for green thresholds ๐Ÿ”œ Planned
v0.7.0 โ˜๏ธ Cloud Dashboard โ€” Real-time emissions visualization web UI ๐Ÿ”œ Planned
v0.7.0 ๐Ÿ“Š Automated ESG Reports โ€” CSRD and GHG Protocol-compliant exports ๐Ÿ”œ Planned
v0.7.x ๐Ÿ”— AWS / Azure / GCP โ€” Cloud resource carbon attribution ๐Ÿ”œ Planned
v0.8.0 ๐Ÿข Team Carbon Budgets โ€” Multi-project rollup with alerting ๐Ÿ”œ Planned

Shape the roadmap: Open an issue or join our Discord to suggest features.


๐Ÿ“ฆ Dependencies

psutil              โ€” Process-level CPU & RAM monitoring
py-cpuinfo          โ€” Hardware identification & CPU detection
fpdf                โ€” PDF report generation
matplotlib          โ€” CPU/GPU usage charting
nvidia-ml-py        โ€” NVIDIA GPU monitoring (optional at runtime)
google-generativeai โ€” Gemini AI Insights engine (optional)
requests            โ€” Live Grid API communication (Electricity Maps)
packaging           โ€” PEP 440 semantic version comparison
wmi                 โ€” AMD/Intel GPU detection (Windows only)

Compatibility: EcoTrace is tested on Python 3.9+ and runs on Windows, macOS, and Linux. GPU features require appropriate vendor drivers.


๐Ÿค Contributing

We welcome contributions from the community! See CONTRIBUTING.MD for guidelines.

Ways to contribute:

  • ๐Ÿ› Report bugs and issues
  • ๐Ÿ’ก Suggest new features
  • ๐Ÿ’ป Submit TDP data for unlisted CPUs
  • ๐Ÿ“ Improve documentation
  • ๐ŸŒ Add region/country support

๐Ÿ‘ค Author

Emre ร–zkal โ€” ecotraceteam@gmail.com


๐Ÿ“„ License

MIT License โ€” use it however you like.


Built with ๐Ÿ’š for a sustainable software future.

Documentation ยท PyPI ยท Discord ยท Issues

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ecotrace-0.6.1.tar.gz (410.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ecotrace-0.6.1-py3-none-any.whl (421.1 kB view details)

Uploaded Python 3

File details

Details for the file ecotrace-0.6.1.tar.gz.

File metadata

  • Download URL: ecotrace-0.6.1.tar.gz
  • Upload date:
  • Size: 410.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.1

File hashes

Hashes for ecotrace-0.6.1.tar.gz
Algorithm Hash digest
SHA256 da7cec8c2340fca739474452b90f9c2db0c10c6adedfb3321fa9031dbaebebf5
MD5 c1ef34b84fa93b764e4e8e54c29fa2f8
BLAKE2b-256 04e1a420775235fc1aecb1f04d25faeba73f6365de7598e2fc19b64c82e5b020

See more details on using hashes here.

File details

Details for the file ecotrace-0.6.1-py3-none-any.whl.

File metadata

  • Download URL: ecotrace-0.6.1-py3-none-any.whl
  • Upload date:
  • Size: 421.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.1

File hashes

Hashes for ecotrace-0.6.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ecae73ca237dd9e3a1d3ab1a453c80a08d265402f084c92081fccd37395e8412
MD5 195ec2bb0019326efbac9450e1b0a496
BLAKE2b-256 4630b91da280748a379eaf4425fa3e77010dc607bd26b9de4e6613d399a97825

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page