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