github.com/mattyr/nomad@v0.3.3-0.20160919021406-3485a065154a/client/stats/cpu.go (about)

     1  package stats
     2  
     3  import (
     4  	"runtime"
     5  	"time"
     6  
     7  	shelpers "github.com/hashicorp/nomad/helper/stats"
     8  )
     9  
    10  // CpuStats calculates cpu usage percentage
    11  type CpuStats struct {
    12  	prevCpuTime float64
    13  	prevTime    time.Time
    14  	clkSpeed    float64
    15  
    16  	totalCpus int
    17  }
    18  
    19  // NewCpuStats returns a cpu stats calculator
    20  func NewCpuStats() *CpuStats {
    21  	numCpus := runtime.NumCPU()
    22  	cpuStats := &CpuStats{
    23  		totalCpus: numCpus,
    24  	}
    25  	return cpuStats
    26  }
    27  
    28  // Percent calculates the cpu usage percentage based on the current cpu usage
    29  // and the previous cpu usage where usage is given as time in nanoseconds spend
    30  // in the cpu
    31  func (c *CpuStats) Percent(cpuTime float64) float64 {
    32  	now := time.Now()
    33  
    34  	if c.prevCpuTime == 0.0 {
    35  		// invoked first time
    36  		c.prevCpuTime = cpuTime
    37  		c.prevTime = now
    38  		return 0.0
    39  	}
    40  
    41  	timeDelta := now.Sub(c.prevTime).Nanoseconds()
    42  	ret := c.calculatePercent(c.prevCpuTime, cpuTime, timeDelta)
    43  	c.prevCpuTime = cpuTime
    44  	c.prevTime = now
    45  	return ret
    46  }
    47  
    48  // TicksConsumed calculates the total ticks consumes by the process across all
    49  // cpu cores
    50  func (c *CpuStats) TicksConsumed(percent float64) float64 {
    51  	return (percent / 100) * shelpers.TotalTicksAvailable() / float64(c.totalCpus)
    52  }
    53  
    54  func (c *CpuStats) calculatePercent(t1, t2 float64, timeDelta int64) float64 {
    55  	vDelta := t2 - t1
    56  	if timeDelta <= 0 || vDelta <= 0.0 {
    57  		return 0.0
    58  	}
    59  
    60  	overall_percent := (vDelta / float64(timeDelta)) * 100.0
    61  	return overall_percent
    62  }