Skip to content

Commit

Permalink
refactor: optimize the process.Percent function
Browse files Browse the repository at this point in the history
  • Loading branch information
Percivalll authored and zhanglei36 committed May 11, 2023
1 parent e045dc7 commit 91248fa
Showing 1 changed file with 5 additions and 13 deletions.
18 changes: 5 additions & 13 deletions process/process.go
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"runtime"
"sort"
"sync"
"time"
Expand Down Expand Up @@ -262,9 +261,11 @@ func (p *Process) PercentWithContext(ctx context.Context, interval time.Duration
}
}

numcpu := runtime.NumCPU()
delta := (now.Sub(p.lastCPUTime).Seconds()) * float64(numcpu)
ret := calculatePercent(p.lastCPUTimes, cpuTimes, delta, numcpu)
delta := now.Sub(p.lastCPUTime).Seconds()
if delta == 0 {
return 0, nil
}
ret := (cpuTimes.Total() - p.lastCPUTimes.Total()) * 100 / delta
p.lastCPUTimes = cpuTimes
p.lastCPUTime = now
return ret, nil
Expand Down Expand Up @@ -305,15 +306,6 @@ func (p *Process) CreateTimeWithContext(ctx context.Context) (int64, error) {
return p.createTime, err
}

func calculatePercent(t1, t2 *cpu.TimesStat, delta float64, numcpu int) float64 {
if delta == 0 {
return 0
}
delta_proc := t2.Total() - t1.Total()
overall_percent := ((delta_proc / delta) * 100) * float64(numcpu)
return overall_percent
}

// MemoryPercent returns how many percent of the total RAM this process uses
func (p *Process) MemoryPercent() (float32, error) {
return p.MemoryPercentWithContext(context.Background())
Expand Down

0 comments on commit 91248fa

Please sign in to comment.