From 946c9ce6ea57f47a8b7b38687f0924e06953e59a Mon Sep 17 00:00:00 2001 From: Lomanic Date: Sun, 23 Jun 2019 16:14:14 +0200 Subject: [PATCH] [cpu] Fix #599 cap percent values returned by Percent() between 0 and 100 See https://github.com/shirou/gopsutil/issues/599#issuecomment-491942842 for a repoduction case --- cpu/cpu.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cpu/cpu.go b/cpu/cpu.go index daf3524..80ce3f0 100644 --- a/cpu/cpu.go +++ b/cpu/cpu.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "math" "strconv" "strings" "sync" @@ -112,7 +113,7 @@ func calculateBusy(t1, t2 TimesStat) float64 { if t2All <= t1All { return 1 } - return (t2Busy - t1Busy) / (t2All - t1All) * 100 + return math.Min(100, math.Max(0, (t2Busy-t1Busy)/(t2All-t1All)*100)) } func calculateAllBusy(t1, t2 []TimesStat) ([]float64, error) {