github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/utils/hwstats/cpu_all.go (about) 1 // Copyright 2023 LiveKit, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package hwstats 16 17 import ( 18 "runtime" 19 20 "github.com/mackerelio/go-osstat/cpu" 21 ) 22 23 type osStatCPUMonitor struct { 24 prev *cpu.Stats 25 } 26 27 func newOSStatCPUMonitor() (*osStatCPUMonitor, error) { 28 stats, err := cpu.Get() 29 if err != nil { 30 return nil, err 31 } 32 33 return &osStatCPUMonitor{ 34 prev: stats, 35 }, nil 36 } 37 38 func (p *osStatCPUMonitor) getCPUIdle() (float64, error) { 39 next, err := cpu.Get() 40 if err != nil { 41 return 0, err 42 } 43 idleRatio := float64(next.Idle-p.prev.Idle) / float64(next.Total-p.prev.Total) 44 p.prev = next 45 46 return p.numCPU() * idleRatio, nil 47 } 48 49 func (p *osStatCPUMonitor) numCPU() float64 { 50 return float64(runtime.NumCPU()) 51 }