github.com/songzhibin97/gkit@v1.2.13/internal/sys/cpu/cpu.go (about) 1 package cpu 2 3 import ( 4 "fmt" 5 "sync/atomic" 6 "time" 7 ) 8 9 const ( 10 interval time.Duration = time.Millisecond * 500 11 ) 12 13 var ( 14 stats CPU 15 usage uint64 16 ) 17 18 // CPU interface 定义CPU用法 19 type CPU interface { 20 Usage() (u uint64, e error) 21 Info() Info 22 } 23 24 func init() { 25 var err error 26 // 判断操作系统使用的是cGroup,如果不是cGroup退化为Psutil 27 stats, err = newCGroupCPU() 28 if err != nil { 29 stats, err = newPsutilCPU(interval) 30 if err != nil { 31 panic(fmt.Sprintf("cGroup cpu init failed!err:=%v", err)) 32 } 33 } 34 // 开启定时任务 35 go func() { 36 ticker := time.NewTicker(interval) 37 defer ticker.Stop() 38 for { 39 <-ticker.C 40 u, err := stats.Usage() 41 if err == nil && u != 0 { 42 atomic.StoreUint64(&usage, u) 43 } 44 } 45 }() 46 } 47 48 // Stat 状态信息 49 type Stat struct { 50 // Usage: CPU使用率 51 Usage uint64 52 } 53 54 // Info 详细信息 55 type Info struct { 56 // Frequency: 频率 57 Frequency uint64 58 // Quota: 磁盘配额 59 Quota float64 60 } 61 62 // ReadStat 读取状态 63 func ReadStat(stat *Stat) { 64 stat.Usage = atomic.LoadUint64(&usage) 65 } 66 67 // GetInfo 获取信息 68 func GetInfo() Info { 69 return stats.Info() 70 }