From f83fa62e886267201a785bc6e7fc5c9c5749b1c5 Mon Sep 17 00:00:00 2001 From: Frank Kusters Date: Tue, 30 Apr 2024 13:08:20 +0200 Subject: [PATCH] Fix too low cpu_times_percent values when interval < ~1 second (#1586) Signed-off-by: Frank Kusters --- CREDITS | 3 +++ HISTORY.rst | 3 +++ psutil/__init__.py | 7 +++---- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CREDITS b/CREDITS index baff0c089..eaeec114d 100644 --- a/CREDITS +++ b/CREDITS @@ -831,3 +831,6 @@ I: 2376 N: Anthony Ryan W: https://github.com/anthonyryan1 I: 2272 + +N: Frank Kusters +I: 1586 diff --git a/HISTORY.rst b/HISTORY.rst index 15333dbaf..2dc33547b 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -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) diff --git a/psutil/__init__.py b/psutil/__init__.py index e1e2b7d5d..39b0adca6 100644 --- a/psutil/__init__.py +++ b/psutil/__init__.py @@ -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)