Skip to content

Commit

Permalink
Merge pull request #135 from influxdata/process-percent
Browse files Browse the repository at this point in the history
Optimize per-process percentage calculation
  • Loading branch information
shirou committed Jan 20, 2016
2 parents 8850f58 + 6688f35 commit 85bf097
Showing 1 changed file with 23 additions and 19 deletions.
42 changes: 23 additions & 19 deletions process/process.go
Expand Up @@ -106,24 +106,15 @@ func PidExists(pid int32) (bool, error) {
// If interval is 0, return difference from last call(non-blocking).
// If interval > 0, wait interval sec and return diffrence between start and end.
func (p *Process) CPUPercent(interval time.Duration) (float64, error) {
numcpu := runtime.NumCPU()
calculate := func(t1, t2 *cpu.CPUTimesStat, delta float64) float64 {
if delta == 0 {
return 0
}
delta_proc := (t2.User - t1.User) + (t2.System - t1.System)
overall_percent := ((delta_proc / delta) * 100) * float64(numcpu)
return overall_percent
}

cpuTimes, err := p.CPUTimes()
if err != nil {
return 0, err
}
now := time.Now()

if interval > 0 {
p.lastCPUTimes = cpuTimes
p.lastCPUTime = time.Now()
p.lastCPUTime = now
time.Sleep(interval)
cpuTimes, err = p.CPUTimes()
if err != nil {
Expand All @@ -132,18 +123,31 @@ func (p *Process) CPUPercent(interval time.Duration) (float64, error) {
} else {
if p.lastCPUTimes == nil {
// invoked first time
p.lastCPUTimes, err = p.CPUTimes()
if err != nil {
return 0, err
}
p.lastCPUTime = time.Now()
p.lastCPUTimes = cpuTimes
p.lastCPUTime = now
return 0, nil
}
}

delta := (time.Now().Sub(p.lastCPUTime).Seconds()) * float64(numcpu)
ret := calculate(p.lastCPUTimes, cpuTimes, float64(delta))
numcpu := runtime.NumCPU()
delta := (now.Sub(p.lastCPUTime).Seconds()) * float64(numcpu)
ret := calculatePercent(p.lastCPUTimes, cpuTimes, delta, numcpu)
p.lastCPUTimes = cpuTimes
p.lastCPUTime = time.Now()
p.lastCPUTime = now
return ret, nil
}

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

func totalCpuTime(t *cpu.CPUTimesStat) float64 {
total := t.User + t.System + t.Nice + t.Iowait + t.Irq + t.Softirq + t.Steal +
t.Guest + t.GuestNice + t.Idle
return total
}

0 comments on commit 85bf097

Please sign in to comment.