Skip to content

Commit 6315615

Browse files
authored
refactor: optimize the process.Percent function
1 parent e045dc7 commit 6315615

File tree

1 file changed

+5
-12
lines changed

1 file changed

+5
-12
lines changed

process/process.go

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -262,9 +262,11 @@ func (p *Process) PercentWithContext(ctx context.Context, interval time.Duration
262262
}
263263
}
264264

265-
numcpu := runtime.NumCPU()
266-
delta := (now.Sub(p.lastCPUTime).Seconds()) * float64(numcpu)
267-
ret := calculatePercent(p.lastCPUTimes, cpuTimes, delta, numcpu)
265+
delta := now.Sub(p.lastCPUTime).Seconds()
266+
if delta == 0 {
267+
return 0, nil
268+
}
269+
ret := (cpuTimes.Total() - p.lastCPUTimes.Total()) * 100 / delta
268270
p.lastCPUTimes = cpuTimes
269271
p.lastCPUTime = now
270272
return ret, nil
@@ -305,15 +307,6 @@ func (p *Process) CreateTimeWithContext(ctx context.Context) (int64, error) {
305307
return p.createTime, err
306308
}
307309

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-
317310
// MemoryPercent returns how many percent of the total RAM this process uses
318311
func (p *Process) MemoryPercent() (float32, error) {
319312
return p.MemoryPercentWithContext(context.Background())

0 commit comments

Comments
 (0)