From ebaa641e63e0119b5b621801154c24abf4c1f10f Mon Sep 17 00:00:00 2001 From: Johan Walles Date: Wed, 10 Feb 2016 17:48:43 +0100 Subject: [PATCH] Make a public function for computing total CPU time This function used to be a private part of process.go. Since I needed that functionality however I think it's better to make it public than for me to copy it into my own code. As a side effect of this change, I also fixed a bug in the function where Stolen was not part of the sum. Having the function close to the CPUTimesStat declaration will make problems like this less likely to re-occur in the future. --- cpu/cpu.go | 7 +++++++ process/process.go | 8 +------- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/cpu/cpu.go b/cpu/cpu.go index fb23a39..d4925aa 100644 --- a/cpu/cpu.go +++ b/cpu/cpu.go @@ -63,6 +63,13 @@ func (c CPUTimesStat) String() string { return `{` + strings.Join(v, ",") + `}` } +// Total returns the total number of seconds in a CPUTimesStat +func (c CPUTimesStat) Total() float64 { + total := c.User + c.System + c.Nice + c.Iowait + c.Irq + c.Softirq + c.Steal + + c.Guest + c.GuestNice + c.Idle + c.Stolen + return total +} + func (c CPUInfoStat) String() string { s, _ := json.Marshal(c) return string(s) diff --git a/process/process.go b/process/process.go index 0a1c3fe..4f63a2a 100644 --- a/process/process.go +++ b/process/process.go @@ -141,13 +141,7 @@ func calculatePercent(t1, t2 *cpu.CPUTimesStat, delta float64, numcpu int) float if delta == 0 { return 0 } - delta_proc := totalCpuTime(t2) - totalCpuTime(t1) + delta_proc := t2.Total() - t1.Total() overall_percent := ((delta_proc / delta) * 100) * float64(numcpu) return overall_percent } - -func totalCpuTime(t *cpu.CPUTimesStat) float64 { - total := t.User + t.System + t.Nice + t.Iowait + t.Irq + t.Softirq + t.Steal + - t.Guest + t.GuestNice + t.Idle - return total -}