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
[!TIP] ๐ VS Code User? Monitor your code's carbon footprint in real-time as you write! Download the EcoTrace VS Code extension.
๐ 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 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 IntegrationReal-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.
eco = EcoTrace(
region_code="TR",
grid_api_key="YOUR_KEY"
)
# Region: TR (482 gCO2/kWh ๐ข LIVE)
|
๐ฑ Auto-Update SystemEcoTrace now checks for updates automatically at startup and asks politely:
|
๐ก 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 GroundedTDP-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 Overhead50 ms daemon-thread sampling with process-scoped isolation. Zero interference with your hot paths. Designed for production, not just benchmarks. |
๐ Compliance-ReadyPer-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
asynciocould reduce idle CPU carbon by 20%." - Library Swaps: "Consider
lxmlinstead ofxml.etreefor this workload to improve efficiency."
Opt-in Feature: Only activated when a valid
GEMINI_API_KEYis 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โ
๐ฅ 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โ
๐ก 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.
๐ฌ 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:
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
|
๐ฎ GPU
|
๐ง RAM
|
๐บ๏ธ 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
da7cec8c2340fca739474452b90f9c2db0c10c6adedfb3321fa9031dbaebebf5
|
|
| MD5 |
c1ef34b84fa93b764e4e8e54c29fa2f8
|
|
| BLAKE2b-256 |
04e1a420775235fc1aecb1f04d25faeba73f6365de7598e2fc19b64c82e5b020
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ecae73ca237dd9e3a1d3ab1a453c80a08d265402f084c92081fccd37395e8412
|
|
| MD5 |
195ec2bb0019326efbac9450e1b0a496
|
|
| BLAKE2b-256 |
4630b91da280748a379eaf4425fa3e77010dc607bd26b9de4e6613d399a97825
|