Skip to content

fix: handle empty power history in CPU.total_power() (#832)#1127

Open
agodianel wants to merge 1 commit intomlco2:masterfrom
agodianel:fix/832-total-power-zero-division
Open

fix: handle empty power history in CPU.total_power() (#832)#1127
agodianel wants to merge 1 commit intomlco2:masterfrom
agodianel:fix/832-total-power-zero-division

Conversation

@agodianel
Copy link

Description

This PR fixes a ZeroDivisionError crash that occurs in the total_power method when the system fails to collect any power samples (resulting in an empty power history).

The previous code checked whether the power history length was 0 immediately after an append call, meaning the condition was a dead code path and never caught the empty list. This has been updated to check for an empty list of watts immediately before the division step, safely returning 0 W instead of crashing.

Related Issue

Fixes #832

Motivation and Context

Prevents CodeCarbon from crashing entirely when hardware sensors (like Intel RAPL or Power Gadget) occasionally fail to return valid readings during a sampling interval.

How Has This Been Tested?

  • Added a regression test that intentionally feeds 0W measurements and clears the power history, asserting that the method handles it gracefully without a ZeroDivisionError.
  • Ran the full test suite to ensure no existing functionality was broken (all CPU and core tests pass successfully).

Types of changes

What types of changes does your code introduce? Put an x in all the boxes that apply:

  • Bug fix (non-breaking change which fixes an issue

@agodianel agodianel requested a review from a team as a code owner March 22, 2026 23:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix crash in total_power() when no power samples are collected

1 participant