Skip to content

Commit

Permalink
Fix too low cpu_times_percent values when interval < ~1 second (#1586)
Browse files Browse the repository at this point in the history
Signed-off-by: Frank Kusters <frank.kusters@sioux.eu>
  • Loading branch information
frankkusters committed Apr 30, 2024
1 parent 0b0ea8e commit f83fa62
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 4 deletions.
3 changes: 3 additions & 0 deletions CREDITS
Original file line number Diff line number Diff line change
Expand Up @@ -831,3 +831,6 @@ I: 2376
N: Anthony Ryan
W: https://github.com/anthonyryan1
I: 2272

N: Frank Kusters
I: 1586
3 changes: 3 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@

**Bug fixes**

- 1586_, `cpu_times_percent()`_ reports much too low values if the interval is
less than 1 second (with ``percpu=True``) or less than ``1/cpu_count()``
seconds (with ``percpu=False``).
- 2395_, [OpenBSD]: `pid_exists()`_ erroneously return True if the argument is
a thread ID (TID) instead of a PID (process ID).
- 2254_, [Linux]: offline cpus raise NotImplementedError in cpu_freq() (patch by Shade Gladden)
Expand Down
7 changes: 3 additions & 4 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1846,10 +1846,9 @@ def calculate(t1, t2):
times_delta = _cpu_times_deltas(t1, t2)
all_delta = _cpu_tot_time(times_delta)
# "scale" is the value to multiply each delta with to get percentages.
# We use "max" to avoid division by zero (if all_delta is 0, then all
# fields are 0 so percentages will be 0 too. all_delta cannot be a
# fraction because cpu times are integers)
scale = 100.0 / max(1, all_delta)
# Avoid division by zero (if all_delta is 0, then all fields are 0 so
# percentages will be 0 too).
scale = 100.0 / all_delta if all_delta > 0 else 100.0
for field_delta in times_delta:
field_perc = field_delta * scale
field_perc = round(field_perc, 1)
Expand Down

0 comments on commit f83fa62

Please sign in to comment.