Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[process] optimize the process.Percent function #1464

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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