From 516a39babea679c5f216c14b7b96720b8ddd2221 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) --- HISTORY.rst | 3 +++ psutil/__init__.py | 7 +++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/HISTORY.rst b/HISTORY.rst index 15333dbaf..1430a2862 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)