Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
1c87924
perf: reduce tracker cold-start and concurrent measurement overhead
davidberenstein1957 Jun 17, 2026
9a5e0ba
perf: prefer fast cpu_load on Mac ARM and fix monitor CLI args
davidberenstein1957 Jun 17, 2026
5afe403
fix: restore test suite compatibility with perf optimizations
davidberenstein1957 Jun 17, 2026
fa53a02
chore: add benchmark and profiling scripts for tracker perf work
davidberenstein1957 Jun 17, 2026
ab9bcec
chore: drop benchmark and profiling scripts from PR
davidberenstein1957 Jun 17, 2026
8f95e9f
fix: resolve CI failures for pre-commit, wheel tests, and coverage
davidberenstein1957 Jun 17, 2026
fe75a1e
fix: make hardware_cache tests portable on Linux CI
davidberenstein1957 Jun 17, 2026
cf356ed
test: raise patch coverage for perf optimization changes
davidberenstein1957 Jun 18, 2026
06d0ede
perf: cache output handlers and add throughput benchmarks
davidberenstein1957 Jun 18, 2026
c961b35
fix: satisfy pre-commit for benchmark scripts
davidberenstein1957 Jun 18, 2026
b06dec3
refactor: drop handler singleton cache, keep targeted perf wins
davidberenstein1957 Jun 18, 2026
2427513
refactor: remove API/output micro-caches and benchmark tooling
davidberenstein1957 Jun 18, 2026
c0ca28e
refactor: simplify probe caches with stdlib lru_cache
davidberenstein1957 Jun 18, 2026
ae79098
fix: avoid eager GPU imports in hardware_cache.clear_cache
davidberenstein1957 Jun 18, 2026
8334302
refactor: use single monitor CLI entry point and update docs
davidberenstein1957 Jun 18, 2026
ab80373
fix: make hardware cache plans fully self-contained
davidberenstein1957 Jun 18, 2026
8ccb30e
test: expect tracking_mode in RAPL CPU setup assertion
davidberenstein1957 Jun 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion codecarbon/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
OfflineEmissionsTracker,
track_emissions,
)
from .output import OutputMethod
from .output_methods.base_output import OutputMethod

__all__ = [
"EmissionsTracker",
Expand Down
40 changes: 33 additions & 7 deletions codecarbon/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,19 @@
from pathlib import Path
from typing import Optional

import questionary
import requests
import typer
from rich import print
from rich.prompt import Confirm
from typing_extensions import Annotated

from codecarbon import __app_name__, __version__
from codecarbon.cli.auth import authorize, get_access_token
from codecarbon.cli.cli_utils import (
create_new_config_file,
get_api_endpoint,
get_config,
get_existing_exp_id,
overwrite_local_config,
)
from codecarbon.cli.monitor import run_and_monitor
from codecarbon.core.api_client import ApiClient, get_datetime_with_timezone
from codecarbon.core.schemas import ExperimentCreate, OrganizationCreate, ProjectCreate
from codecarbon.emissions_tracker import EmissionsTracker, OfflineEmissionsTracker

API_URL = os.environ.get("API_URL", "https://dashboard.codecarbon.io/api")

Expand Down Expand Up @@ -68,6 +61,9 @@ def version(


def show_config(path: Path = Path("./.codecarbon.config")) -> None:
from codecarbon.cli.auth import get_access_token
from codecarbon.core.api_client import ApiClient

d = get_config(path)
print("Current configuration : \n")
print("Config file content : ")
Expand Down Expand Up @@ -114,6 +110,9 @@ def api_get():
"""
ex: test-api
"""
from codecarbon.cli.auth import get_access_token
from codecarbon.core.api_client import ApiClient

api_endpoint = get_api_endpoint()
api = ApiClient(endpoint_url=api_endpoint)
api.set_access_token(get_access_token())
Expand All @@ -123,6 +122,9 @@ def api_get():

@codecarbon.command("login", short_help="Login to CodeCarbon")
def login():
from codecarbon.cli.auth import authorize, get_access_token
from codecarbon.core.api_client import ApiClient

authorize()
api_endpoint = get_api_endpoint()
api = ApiClient(endpoint_url=api_endpoint)
Expand All @@ -132,6 +134,10 @@ def login():


def get_api_key(project_id: str):
import requests

from codecarbon.cli.auth import get_access_token

api_endpoint = get_api_endpoint()
api_endpoint = api_endpoint.rstrip("/")
req = requests.post(
Expand Down Expand Up @@ -161,6 +167,13 @@ def config():
"""
Initialize CodeCarbon, this will prompt you for configuration of Organisation/Team/Project/Experiment.
"""
from codecarbon.cli.auth import get_access_token
from codecarbon.core.api_client import ApiClient, get_datetime_with_timezone
from codecarbon.core.schemas import (
ExperimentCreate,
OrganizationCreate,
ProjectCreate,
)

print("Welcome to CodeCarbon configuration wizard")
home = Path.home()
Expand Down Expand Up @@ -342,13 +355,18 @@ def monitor(
str,
typer.Option(help="Region/province for offline mode"),
] = None,
log_level: Annotated[
str,
typer.Option(help="Log level (critical, error, warning, info, debug)"),
] = "error",
):
"""Monitor your machine's carbon emissions."""

# Shared tracker args so monitor and run_and_monitor behave the same
tracker_args = {
"measure_power_secs": measure_power_secs,
"api_call_interval": api_call_interval,
"log_level": log_level,
}
# Set up the tracker arguments based on mode (offline vs online) and validate required args for each mode
if offline:
Expand All @@ -375,8 +393,12 @@ def monitor(

tracker_args = {**tracker_args, "save_to_api": api}

from codecarbon.emissions_tracker import EmissionsTracker, OfflineEmissionsTracker

# If extra args are provided (e.g. `codecarbon monitor -- my_script.py`), delegate to `run_and_monitor`
if getattr(ctx, "args", None):
from codecarbon.cli.monitor import run_and_monitor

return run_and_monitor(ctx, offline=offline, **tracker_args)

# Instantiate the tracker
Expand Down Expand Up @@ -417,6 +439,8 @@ def detect():
"""
Detects hardware and prints information without running any measurements.
"""
from codecarbon.emissions_tracker import EmissionsTracker

print("Detecting hardware...")
tracker = EmissionsTracker(save_to_file=False)
hardware_info = tracker.get_detected_hardware()
Expand All @@ -438,6 +462,8 @@ def detect():


def questionary_prompt(prompt, list_options, default):
import questionary

value = questionary.select(
prompt,
list_options,
Expand Down
9 changes: 5 additions & 4 deletions codecarbon/cli/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
from rich import print
from typing_extensions import Annotated

from codecarbon.emissions_tracker import EmissionsTracker, OfflineEmissionsTracker


def run_and_monitor(
ctx: typer.Context,
Expand Down Expand Up @@ -50,12 +48,15 @@ def run_and_monitor(
directory. The file path is shown in the final report.
"""
# Suppress all CodeCarbon logs during execution
from codecarbon.emissions_tracker import EmissionsTracker, OfflineEmissionsTracker
from codecarbon.external.logger import set_logger_level

set_logger_level(log_level)

# Get the command from remaining args
command = ctx.args
# Get the command from remaining args (strip nested subcommand / `--` leftovers)
command = list(getattr(ctx, "args", None) or [])
while command and command[0] in ("monitor", "--"):
command.pop(0)

if not command:
print(
Expand Down
8 changes: 3 additions & 5 deletions codecarbon/core/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import json
from datetime import timedelta, tzinfo

import arrow
import requests

from codecarbon.core.schemas import (
Expand All @@ -22,12 +21,11 @@
)
from codecarbon.external.logger import logger

# from codecarbon.output import EmissionsData


def get_datetime_with_timezone():
timestamp = str(arrow.now().isoformat())
return timestamp
import arrow

return str(arrow.now().isoformat())


class ApiClient: # (AsyncClient)
Expand Down
20 changes: 14 additions & 6 deletions codecarbon/core/cpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,29 @@
https://software.intel.com/content/www/us/en/develop/articles/intel-power-gadget.html
"""

from __future__ import annotations

import os
import re
import shutil
import subprocess
import sys
from functools import lru_cache
from typing import Dict, Optional, Tuple

import pandas as pd
import psutil
from rapidfuzz import fuzz, process, utils

from codecarbon.core.rapl import RAPLFile
from codecarbon.core.units import Time
from codecarbon.core.util import count_cpus, detect_cpu_model
from codecarbon.external.logger import logger
from codecarbon.input import DataSource

# default W value per core for a CPU if no model is found in the ref csv
DEFAULT_POWER_PER_CORE = 4


@lru_cache(maxsize=1)
def is_powergadget_available() -> bool:
"""
Checks if Intel Power Gadget is available on the system.
Expand All @@ -44,6 +46,10 @@ def is_powergadget_available() -> bool:
return False


def clear_powergadget_cache() -> None:
is_powergadget_available.cache_clear()


def _get_candidate_bases(rapl_dir: str) -> list:
"""Get list of directories to scan for RAPL files."""
default_rapl_dir = "/sys/class/powercap/intel-rapl/subsystem"
Expand Down Expand Up @@ -366,6 +372,8 @@ def get_cpu_details(self) -> Dict:
self._log_values()
cpu_details = {}
try:
import pandas as pd

cpu_data = pd.read_csv(self._log_file_path).dropna()
for col_name in cpu_data.columns:
if col_name in ["System Time", "Elapsed Time (sec)", "RDTSC"]:
Expand Down Expand Up @@ -887,21 +895,21 @@ def __init__(self):
self.model, self.tdp = self._main()

@staticmethod
def _get_cpu_constant_power(match: str, cpu_power_df: pd.DataFrame) -> int:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not delete this, if we are using pandas only for typing we can do

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    import pandas as pd

def _get_cpu_constant_power(match: str, cpu_power_df) -> int:
"""Extract constant power from matched CPU"""
return float(cpu_power_df[cpu_power_df["Name"] == match]["TDP"].values[0])

def _get_cpu_power_from_registry(self, cpu_model_raw: str) -> Optional[int]:
from codecarbon.input import DataSource

cpu_power_df = DataSource().get_cpu_power_data()
cpu_matching = self._get_matching_cpu(cpu_model_raw, cpu_power_df)
if cpu_matching:
power = self._get_cpu_constant_power(cpu_matching, cpu_power_df)
return power
return None

def _get_matching_cpu(
self, model_raw: str, cpu_df: pd.DataFrame, greedy=False

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same

) -> str:
def _get_matching_cpu(self, model_raw: str, cpu_df, greedy=False) -> str:
"""
Get matching cpu name

Expand Down
10 changes: 4 additions & 6 deletions codecarbon/core/emissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@

from typing import Dict, Optional

import pandas as pd

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same in this file

from codecarbon.core import electricitymaps_api
from codecarbon.core.units import EmissionsPerKWh, Energy
from codecarbon.external.geography import CloudMetadata, GeoMetadata
Expand Down Expand Up @@ -64,7 +62,7 @@ def get_cloud_emissions(
)
return energy.kWh * (self._force_carbon_intensity_g_co2e_kwh / 1000.0)

df: pd.DataFrame = self._data_source.get_cloud_emissions_data()
df = self._data_source.get_cloud_emissions_data()
try:
emissions_per_kWh: EmissionsPerKWh = EmissionsPerKWh.from_g_per_kWh(
df.loc[
Expand Down Expand Up @@ -99,7 +97,7 @@ def get_cloud_country_name(self, cloud: CloudMetadata) -> str:
"""
Returns the Country Name where the cloud region is located
"""
df: pd.DataFrame = self._data_source.get_cloud_emissions_data()
df = self._data_source.get_cloud_emissions_data()
flags = (df["provider"] == cloud.provider) & (df["region"] == cloud.region)
selected = df.loc[flags]
if not len(selected):
Expand All @@ -114,7 +112,7 @@ def get_cloud_country_iso_code(self, cloud: CloudMetadata) -> str:
"""
Returns the Country ISO Code where the cloud region is located
"""
df: pd.DataFrame = self._data_source.get_cloud_emissions_data()
df = self._data_source.get_cloud_emissions_data()
flags = (df["provider"] == cloud.provider) & (df["region"] == cloud.region)
selected = df.loc[flags]
if not len(selected):
Expand All @@ -129,7 +127,7 @@ def get_cloud_geo_region(self, cloud: CloudMetadata) -> str:
"""
Returns the State/City where the cloud region is located
"""
df: pd.DataFrame = self._data_source.get_cloud_emissions_data()
df = self._data_source.get_cloud_emissions_data()
flags = (df["provider"] == cloud.provider) & (df["region"] == cloud.region)
selected = df.loc[flags]
if not len(selected):
Expand Down
7 changes: 6 additions & 1 deletion codecarbon/core/gpu_amd.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
import subprocess
from collections import namedtuple
from functools import lru_cache
from typing import Callable

from codecarbon.core.gpu_device import GPUDevice
from codecarbon.external.logger import logger


@lru_cache(maxsize=1)
def is_rocm_system():
"""Returns True if the system has an rocm-smi interface."""
try:
# Check if rocm-smi is available
subprocess.check_output(["rocm-smi", "--help"])
return True
except (subprocess.CalledProcessError, OSError):
return False


def clear_rocm_system_cache() -> None:
is_rocm_system.cache_clear()


try:
import amdsmi

Expand Down
7 changes: 6 additions & 1 deletion codecarbon/core/gpu_nvidia.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
import subprocess
from dataclasses import dataclass
from functools import lru_cache
from typing import Any, Union

from codecarbon.core.gpu_device import GPUDevice
from codecarbon.external.logger import logger


@lru_cache(maxsize=1)
def is_nvidia_system():
"""Returns True if the system has an nvidia-smi interface."""
try:
# Check if nvidia-smi is available
subprocess.check_output(["nvidia-smi", "--help"])
return True
except Exception:
return False


def clear_nvidia_system_cache() -> None:
is_nvidia_system.cache_clear()


try:
import pynvml

Expand Down
Loading
Loading