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