github.com/whoyao/protocol@v0.0.0-20230519045905-2d8ace718ca5/utils/cpu_all.go (about)

     1  package utils
     2  
     3  import (
     4  	"runtime"
     5  
     6  	"github.com/mackerelio/go-osstat/cpu"
     7  )
     8  
     9  type osstatCPUMonitor struct {
    10  	prev *cpu.Stats
    11  }
    12  
    13  func newOsstatCPUMonitor() (*osstatCPUMonitor, error) {
    14  	stats, err := cpu.Get()
    15  	if err != nil {
    16  		return nil, err
    17  	}
    18  
    19  	return &osstatCPUMonitor{
    20  		prev: stats,
    21  	}, nil
    22  }
    23  
    24  func (p *osstatCPUMonitor) getCPUIdle() (float64, error) {
    25  	next, err := cpu.Get()
    26  	if err != nil {
    27  		return 0, err
    28  	}
    29  	idleRatio := float64(next.Idle-p.prev.Idle) / float64(next.Total-p.prev.Total)
    30  	p.prev = next
    31  
    32  	return float64(p.numCPU()) * idleRatio, nil
    33  }
    34  
    35  func (p *osstatCPUMonitor) numCPU() int {
    36  	return runtime.NumCPU()
    37  }