Skip to content

is_psutil_available() returns False on macOS because psutil.cpu_times().nice is always 0 #1210

@tarahmarie

Description

@tarahmarie

Describe the bug

codecarbon/core/cpu.py:is_psutil_available() always returns False on macOS, even when psutil is installed and fully functional. This forces CodeCarbon to fall back to powermetrics, which requires sudo and breaks tracking on machines where users don't have admin rights linke on university-managed laptops, CI runners, and restricted dev environments.

The function uses psutil.cpu_times().nice > 0.0001 as its primary availability heuristic. On Darwin, psutil.cpu_times().nice is always reported as 0.0 bc Darwin's kernel does not aggregate nice CPU time the way the Linux kernel does. The nice-based fast path therefore returns False on every macOS bare metal host, which was a very annoying find. :/

To Reproduce

On any macOS machine with psutil installed:

python3 -c "import psutil; print(psutil.cpu_times().nice)"

then open a python session:

from codecarbon.core.cpu import is_psutil_available
is_psutil_available()
# Returns: False
# Debug log: "is_psutil_available(): psutil.cpu_times().nice is too small: 0.0"

import psutil
psutil.cpu_percent(interval=0.0, percpu=False)
# Returns a valid float on the same machine

I think the fix is:

def is_psutil_available():
    try:
        cpu_times = psutil.cpu_times()

        if hasattr(cpu_times, "nice"):
            nice = cpu_times.nice
            if nice > 0.0001:
                return True
            # nice attribute exists but is always 0 on Darwin --
            # fall through to the cpu_percent test below, same as Windows.
            logger.debug(
                f"is_psutil_available(): nice is too small ({nice}); "
                "trying cpu_percent fallback."
            )

        # Fallback: works on Windows (no nice attribute) and on
        # macOS/Darwin (nice present but always 0).
        psutil.cpu_percent(interval=0.0, percpu=False)
        return True

    except Exception as e:
        logger.debug(
            "Not using the psutil interface, an exception occurred while "
            f"instantiating psutil.cpu_times: {e}",
        )
        return False

Expected behavior

The thing runs and doesn't threaten to report me for not being in /etc/sudoers . :-)

Desktop (please complete the following information):

  • OS: macOS 26.5 (Apple Silicon, arm64)
  • Python Version: 3.11.7
  • CodeCarbon Version: 3.2.6
  • psutil Version: 7.2.2

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions