github.com/maier/nomad@v0.4.1-0.20161110003312-a9e3d0b8549d/helper/stats/cpu.go (about)

     1  package stats
     2  
     3  import (
     4  	"fmt"
     5  	"math"
     6  	"sync"
     7  
     8  	"github.com/shirou/gopsutil/cpu"
     9  )
    10  
    11  var (
    12  	cpuMhzPerCore float64
    13  	cpuModelName  string
    14  	cpuNumCores   int
    15  	cpuTotalTicks float64
    16  
    17  	onceLer sync.Once
    18  )
    19  
    20  func Init() error {
    21  	var err error
    22  	onceLer.Do(func() {
    23  		if cpuNumCores, err = cpu.Counts(true); err != nil {
    24  			err = fmt.Errorf("Unable to determine the number of CPU cores available: %v", err)
    25  			return
    26  		}
    27  
    28  		var cpuInfo []cpu.InfoStat
    29  		if cpuInfo, err = cpu.Info(); err != nil {
    30  			err = fmt.Errorf("Unable to obtain CPU information: %v", err)
    31  			return
    32  		}
    33  
    34  		for _, cpu := range cpuInfo {
    35  			cpuModelName = cpu.ModelName
    36  			cpuMhzPerCore = cpu.Mhz
    37  			break
    38  		}
    39  
    40  		// Floor all of the values such that small difference don't cause the
    41  		// node to fall into a unique computed node class
    42  		cpuMhzPerCore = math.Floor(cpuMhzPerCore)
    43  		cpuTotalTicks = math.Floor(float64(cpuNumCores) * cpuMhzPerCore)
    44  	})
    45  	return err
    46  }
    47  
    48  // CPUModelName returns the number of CPU cores available
    49  func CPUNumCores() int {
    50  	return cpuNumCores
    51  }
    52  
    53  // CPUMHzPerCore returns the MHz per CPU core
    54  func CPUMHzPerCore() float64 {
    55  	return cpuMhzPerCore
    56  }
    57  
    58  // CPUModelName returns the model name of the CPU
    59  func CPUModelName() string {
    60  	return cpuModelName
    61  }
    62  
    63  // TotalTicksAvailable calculates the total frequency available across all
    64  // cores
    65  func TotalTicksAvailable() float64 {
    66  	return cpuTotalTicks
    67  }