Skip to content

Commit

Permalink
[process] Fix shirou#599 cap percent values returned by *Percent() be…
Browse files Browse the repository at this point in the history
…tween 0 and 100
  • Loading branch information
Lomanic committed Jul 7, 2019
1 parent 428e65c commit f4e2355
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions process/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"math"
"runtime"
"time"

Expand Down Expand Up @@ -212,7 +213,7 @@ func calculatePercent(t1, t2 *cpu.TimesStat, delta float64, numcpu int) float64
}
delta_proc := t2.Total() - t1.Total()
overall_percent := ((delta_proc / delta) * 100) * float64(numcpu)
return overall_percent
return math.Min(100, math.Max(0, overall_percent))
}

// MemoryPercent returns how many percent of the total RAM this process uses
Expand All @@ -233,7 +234,7 @@ func (p *Process) MemoryPercentWithContext(ctx context.Context) (float32, error)
}
used := processMemory.RSS

return (100 * float32(used) / float32(total)), nil
return float32(math.Min(100, math.Max(0, (100*float64(used)/float64(total))))), nil
}

// CPU_Percent returns how many percent of the CPU time this process uses
Expand All @@ -258,5 +259,5 @@ func (p *Process) CPUPercentWithContext(ctx context.Context) (float64, error) {
return 0, nil
}

return 100 * cput.Total() / totalTime, nil
return math.Min(100, math.Max(0, 100*cput.Total()/totalTime)), nil
}

0 comments on commit f4e2355

Please sign in to comment.