Skip to content

Commit 91248fa

Browse files
Percivalllzhanglei36
authored andcommitted
refactor: optimize the process.Percent function
1 parent e045dc7 commit 91248fa

File tree

1 file changed

+5
-13
lines changed

1 file changed

+5
-13
lines changed

process/process.go

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"context"
55
"encoding/json"
66
"errors"
7-
"runtime"
87
"sort"
98
"sync"
109
"time"
@@ -262,9 +261,11 @@ func (p *Process) PercentWithContext(ctx context.Context, interval time.Duration
262261
}
263262
}
264263

265-
numcpu := runtime.NumCPU()
266-
delta := (now.Sub(p.lastCPUTime).Seconds()) * float64(numcpu)
267-
ret := calculatePercent(p.lastCPUTimes, cpuTimes, delta, numcpu)
264+
delta := now.Sub(p.lastCPUTime).Seconds()
265+
if delta == 0 {
266+
return 0, nil
267+
}
268+
ret := (cpuTimes.Total() - p.lastCPUTimes.Total()) * 100 / delta
268269
p.lastCPUTimes = cpuTimes
269270
p.lastCPUTime = now
270271
return ret, nil
@@ -305,15 +306,6 @@ func (p *Process) CreateTimeWithContext(ctx context.Context) (int64, error) {
305306
return p.createTime, err
306307
}
307308

308-
func calculatePercent(t1, t2 *cpu.TimesStat, delta float64, numcpu int) float64 {
309-
if delta == 0 {
310-
return 0
311-
}
312-
delta_proc := t2.Total() - t1.Total()
313-
overall_percent := ((delta_proc / delta) * 100) * float64(numcpu)
314-
return overall_percent
315-
}
316-
317309
// MemoryPercent returns how many percent of the total RAM this process uses
318310
func (p *Process) MemoryPercent() (float32, error) {
319311
return p.MemoryPercentWithContext(context.Background())

0 commit comments

Comments
 (0)