open-nomad/client/stats/cpu.go

49 lines
1011 B
Go
Raw Normal View History

2016-05-19 20:32:03 +00:00
package stats
import (
"log"
"runtime"
"time"
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
logger *log.Logger
2016-05-19 20:32:03 +00:00
}
func NewCpuStats(logger *log.Logger) *CpuStats {
numCpus := runtime.NumCPU()
return &CpuStats{totalCpus: numCpus, logger: logger}
2016-05-19 20:32:03 +00:00
}
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
}