From 829f2fafbdcf538249414a07fcb2943b1c605f56 Mon Sep 17 00:00:00 2001 From: Cnpt <44840184+TheBestLL@users.noreply.github.com> Date: Sat, 24 Aug 2024 20:46:32 +0800 Subject: [PATCH] Refactoring the algorithm for calculating CPU usage (#1692) refactor(process): Refactoring the algorithm for calculating CPU usage --- process/process.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/process/process.go b/process/process.go index deba7c7b1..d73f1f972 100644 --- a/process/process.go +++ b/process/process.go @@ -325,7 +325,11 @@ func calculatePercent(t1, t2 *cpu.TimesStat, delta float64, numcpu int) float64 if delta == 0 { return 0 } - delta_proc := t2.Total() - t1.Total() + // https://github.com/giampaolo/psutil/blob/c034e6692cf736b5e87d14418a8153bb03f6cf42/psutil/__init__.py#L1064 + delta_proc := (t2.User - t1.User) + (t2.System - t1.System) + if delta_proc <= 0 { + return 0 + } overall_percent := ((delta_proc / delta) * 100) * float64(numcpu) return overall_percent }