open-nomad/client/stats/cpu.go

51 lines
1.1 KiB
Go
Raw Normal View History

2016-05-19 20:32:03 +00:00
package stats
import (
"runtime"
"time"
2016-05-19 20:32:03 +00:00
)
2016-05-20 18:38:15 +00:00
// CpuStats calculates cpu usage percentage
2016-05-19 20:32:03 +00:00
type CpuStats struct {
prevProcessUsage float64
prevTime time.Time
2016-05-19 20:32:03 +00:00
totalCpus int
}
2016-05-20 18:38:15 +00:00
// NewCpuStats returns a cpu stats calculator
2016-05-21 06:16:24 +00:00
func NewCpuStats() *CpuStats {
numCpus := runtime.NumCPU()
2016-05-21 06:16:24 +00:00
return &CpuStats{totalCpus: numCpus}
2016-05-19 20:32:03 +00:00
}
2016-05-20 18:38:15 +00:00
// Percent calculates the cpu usage percentage based on the current cpu usage
// and the previous cpu usage
func (c *CpuStats) Percent(currentProcessUsage float64) float64 {
2016-05-20 09:10:50 +00:00
now := time.Now()
if c.prevProcessUsage == 0.0 {
// invoked first time
c.prevProcessUsage = currentProcessUsage
c.prevTime = now
return 0.0
}
numcpu := runtime.NumCPU()
delta := (now.Sub(c.prevTime).Seconds()) * float64(numcpu)
ret := c.calculatePercent(c.prevProcessUsage, currentProcessUsage, delta, numcpu)
2016-05-19 20:32:03 +00:00
c.prevProcessUsage = currentProcessUsage
2016-05-20 09:10:50 +00:00
c.prevTime = now
return ret
}
2016-05-20 09:10:50 +00:00
func (c *CpuStats) calculatePercent(t1, t2 float64, delta float64, numcpu int) float64 {
if delta == 0 {
return 0
}
delta_proc := t2 - t1
overall_percent := ((delta_proc / delta) * 100) * float64(numcpu)
return overall_percent
2016-05-19 20:32:03 +00:00
}