From 696e1e0123aeee6b0f6de5ceeae0107e3f407911 Mon Sep 17 00:00:00 2001 From: Kemal Hadimli Date: Thu, 28 Sep 2017 14:34:12 +0300 Subject: [PATCH 1/3] Fix NaN percentage if process was created too soon --- process/process.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/process/process.go b/process/process.go index 8393049..504d7d4 100644 --- a/process/process.go +++ b/process/process.go @@ -207,12 +207,13 @@ func (p *Process) CPUPercent() (float64, error) { } - cpu, err := p.Times() + cput, err := p.Times() if err != nil { return 0, err } + created := time.Unix(0, crt_time * int64(time.Millisecond)) + totalTime := time.Since(created).Seconds() - return (100 * (cpu.Total()) / float64(time.Now().Unix()-(crt_time/1000))), nil + return (100 * (cput.Total() / totalTime)), nil } - From a3144a6850533d51248bfe549adaa5b0d6fbdbbc Mon Sep 17 00:00:00 2001 From: Kemal Hadimli Date: Thu, 28 Sep 2017 14:43:04 +0300 Subject: [PATCH 2/3] Remove parens --- process/process.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/process/process.go b/process/process.go index 504d7d4..cc72dc2 100644 --- a/process/process.go +++ b/process/process.go @@ -215,5 +215,5 @@ func (p *Process) CPUPercent() (float64, error) { created := time.Unix(0, crt_time * int64(time.Millisecond)) totalTime := time.Since(created).Seconds() - return (100 * (cput.Total() / totalTime)), nil + return 100 * cput.Total() / totalTime, nil } From 826e63acbca9034534d6e2c050457841d6e65dc1 Mon Sep 17 00:00:00 2001 From: Kemal Hadimli Date: Thu, 28 Sep 2017 15:54:06 +0300 Subject: [PATCH 3/3] Never divide by zero --- process/process.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/process/process.go b/process/process.go index cc72dc2..cb91674 100644 --- a/process/process.go +++ b/process/process.go @@ -214,6 +214,9 @@ func (p *Process) CPUPercent() (float64, error) { created := time.Unix(0, crt_time * int64(time.Millisecond)) totalTime := time.Since(created).Seconds() + if totalTime <= 0 { + return 0, nil + } return 100 * cput.Total() / totalTime, nil }