Skip to main content

💡 GreenTrace: Effortless CO₂ Emissions Tracking for Python Code

PyPI version License: MIT

Track the carbon footprint of your Python functions and code blocks with ease. Works seamlessly in both synchronous and asynchronous applications.

GreenTrace is a lightweight, simple, and powerful tool for measuring the energy consumption and estimating the CO₂ emissions of your Python code. It requires no external APIs, accounts, or permissions to get started. Just install, import, and add a decorator or a context manager.


Key Features

  • Effortless Integration: Use a simple decorator (@track_emissions) or a context manager to start tracking without refactoring your code.
  • Works Offline, No API Keys: All carbon intensity data is included in the library. It works out-of-the-box without any network requests, API keys, or registration.
  • Native Async Support: GreenTrace is designed for modern Python and works flawlessly with async and await syntax, a feature often missing in other trackers.
  • Lightweight with Minimal Dependencies: Built to be lean, GreenTrace adds minimal overhead to your project.
  • Accurate Hardware Monitoring: On Linux, it uses Intel's RAPL interface for precise CPU energy readings where available. On other systems, it uses a reliable model based on CPU load and Thermal Design Power (TDP).
  • Beautiful, Shareable Reports: Generate reports as console output, JSON, CSV, or a stunning, self-contained HTML certificate perfect for sharing your results.

Why track emissions?

Understanding the carbon footprint of your software is the first step toward building more sustainable and efficient applications. GreenTrace helps you:

  • Benchmark the efficiency of different algorithms.
  • Identify energy-hungry parts of your code.
  • Promote green coding practices in your team.
  • Report on the environmental impact of your computations.

Installation

Install with your favorite package manager.

Using pip:

pip install GreenTrace

Using uv:

uv add GreenTrace

How to Use

GreenTrace can be used as a decorator or a context manager.

1. As a Decorator

This is the simplest way. Just add @track_emissions to any function. It works for both def and async def functions automatically.

For a standard synchronous function:

from GreenTrace import track_emissions
import time

@track_emissions(region="FR", output_format="console")
def my_heavy_computation():
    # This function performs some CPU-intensive work
    print("Running a heavy computation...")
    start_time = time.time()
    while time.time() - start_time < 10:
        _ = [i*i for i in range(10000)]
    print("Computation finished.")

if __name__ == "__main__":
    my_heavy_computation()

For an asynchronous function:

import asyncio
from GreenTrace import track_emissions

@track_emissions(region="DE", output_file="async_report.html")
async def my_async_task():
    print("Starting async task...")
    await asyncio.sleep(5)
    print("Async task finished.")

if __name__ == "__main__":
    asyncio.run(my_async_task())

2. As a Context Manager

If you want to track a specific block of code instead of an entire function, use a context manager.

Synchronous with block:

from GreenTrace import EmissionsTracker
import time

with EmissionsTracker(region="US", output_file="report.json"):
    print("Tracking a specific block of code...")
    time.sleep(3)
    # ... your code here ...
    print("Block finished.")

Asynchronous async with block:

import asyncio
from GreenTrace import EmissionsTracker

async def main():
    async with EmissionsTracker(region="CN", output_file="report.csv", csv_summary_only=True):
        print("Tracking an async block...")
        await asyncio.sleep(2)
        print("Async block finished.")

if __name__ == "__main__":
    asyncio.run(main())

3. Live Monitoring (for long-running tasks)

If you have a long-running process, like a machine learning training job or a complex API task, you might want to check its carbon footprint while it's still running. GreenTrace makes this easy.

  1. Name your tracker: When you start the tracker (using the decorator or context manager), give it a unique name.
  2. Get the active tracker: From another thread or a different part of your code, use EmissionsTracker.get_active_tracker('your_task_name').
  3. Fetch current data: Call get_current_data() on the tracker instance.

This is particularly useful for REST APIs where you could have one endpoint start a task and another endpoint check its status.

Example:

Imagine you have a long-running task and a separate function to monitor it.

import time
import threading
from GreenTrace import EmissionsTracker, track_emissions, TrackerNotRunningError

# 1. Define and name the task to be tracked
@track_emissions(interval_seconds=2, name="my_ml_job", silent=True)
def long_running_ml_job():
    print("Starting a long-running machine learning job...")
    time.sleep(10)
    print("ML job finished.")

# 2. Create a separate function to monitor the task
def monitor_job():
    print("--- Monitoring started ---")
    while True:
        try:
            tracker = EmissionsTracker.get_active_tracker("my_ml_job")
            data = tracker.get_current_data()
            emissions = data["summary"]["emissions_gco2eq"]
            duration = data["summary"]["duration_seconds"]
            print(f"Live status: {emissions:.4f} gCO₂eq over {duration:.2f} seconds.")
            time.sleep(3)
        except TrackerNotRunningError:
            print("--- Monitoring finished (task completed) ---")
            break

Reporting

GreenTrace can generate reports in multiple formats. You can control this with the output_format and output_file parameters.

HTML Report

The most visually impressive output is the HTML certificate. It's a single, self-contained file that you can easily share.

Example (async_report.html):

https://freeimage.host/i/qqq26qF

To generate it, set the output file to have an .html extension:

@track_emissions(output_file="my_certificate.html")
def my_function():
    # ...

Other Formats

  • JSON: output_file="report.json"
  • CSV: output_file="report.csv"
  • Console: The default if no output_file is specified.

Configuration

The track_emissions decorator and EmissionsTracker class accept several arguments:

  • region (str): The two-letter country code (e.g., "US", "DE", "CN") to use for carbon intensity data. Defaults to a global average.
  • interval_seconds (float): How often to take a power measurement. Default is 5.
  • output_file (str): Path to save the report file. If not provided, prints to console.
  • output_format (str): console, json, csv, html. If an output_file is provided, the format is inferred from the file extension, otherwise defaults to console.
  • csv_summary_only (bool): If True and format is csv, only the summary row is saved.
  • silent (bool): If True, suppresses all console output during tracking.

How It Works

GreenTrace runs a background thread (or an asyncio.Task in async mode) that periodically measures the power consumption of your CPU.

  1. Power Measurement: It uses the most accurate method available for your system. For Linux systems with Intel CPUs, it reads from the Intel RAPL (Running Average Power Limit) interface. For other systems, it estimates power based on current CPU utilization and the processor's TDP (Thermal Design Power).
  2. Energy Calculation: It integrates the power measurements over the tracking duration to calculate the total energy consumed in kilowatt-hours (kWh).
  3. Emissions Estimation: The total energy is multiplied by the carbon intensity factor (in gCO₂eq/kWh) for the specified geographical region to estimate the total CO₂ equivalent emissions.

Contributing

Contributions are welcome! If you have ideas for new features, find a bug, or want to improve the documentation, please open an issue or submit a pull request.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Metadata

Release files for GreenTrace 0.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for GreenTrace 0.2.2
File Size Uploaded Provenance
greentrace-0.2.2.tar.gz 16.1 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for GreenTrace 0.2.2
File Interpreter ABI Platform
greentrace-0.2.2-py3-none-any.whl Python 3 none any Details

Total release size: 34.6 kB

Release files / greentrace-0.2.2.tar.gz

Download URL greentrace-0.2.2.tar.gz
Size 16.1 kB
Tags Source
SHA-256 checksum
How to use checksums
6ba78e5b2c8f52cc49267d3f9a2953e7dc4c14defd82cb40c2151eb51dcacb23
BLAKE2b-256 checksum
How to use checksums
d217e0ef7e69be26454d7bc0646b8559ca1e46c9834efad7ea3d4401b3546e63
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.6.10

Release files / greentrace-0.2.2-py3-none-any.whl

Download URL greentrace-0.2.2-py3-none-any.whl
Size 18.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6a55c2e9aff77ef3571e2a4bb0df0e001087cf15265e816340443ac519b76fca
BLAKE2b-256 checksum
How to use checksums
5aa3692fe5d0b846f4d802888795a43d477c8635b46fa4611514dca98ae89f48
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.6.10

Security for GreenTrace 0.2.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page