当前位置 : 主页 > 网络编程 > PHP >

Go语言学习日记【二十三】监控linux系统cpu使用率与空置率

来源:互联网 收集:自由互联 发布时间:2023-10-08
package main import ( "fmt" "math" "time" sigar "github.com/elastic/gosigar" ) type Monitor struct { lastSample *sigar.Cpu } type Percentages struct { User float64 System float64 Idle float64 IOWait float64 IRQ float64 Nice float64 SoftIRQ


package main


import (
"fmt"
"math"
"time"
sigar "github.com/elastic/gosigar"
)



type Monitor struct {
lastSample *sigar.Cpu
}


type Percentages struct {
User float64
System float64
Idle float64
IOWait float64
IRQ float64
Nice float64
SoftIRQ float64
Steal float64
Total float64
}


type Metrics struct {
previousSample *sigar.Cpu
currentSample *sigar.Cpu
}


func main() {
fmt.Println("Start test")
cpu := new(Monitor)
for {
sample ,_:= cpu.Sample()
pct := sample.Percentages()
fmt.Println("----",pct.User,pct.System,pct.Idle,pct.Total)
time.Sleep(1 * time.Second )
}

}


func (m *Monitor) Sample() (*Metrics, error) {
cpuSample := &sigar.Cpu{}
if err := cpuSample.Get(); err != nil {
return nil, err
}

oldLastSample := m.lastSample
m.lastSample = cpuSample
return &Metrics{oldLastSample, cpuSample}, nil
}


func (m *Metrics) Percentages() Percentages {
return cpuPercentages(m.previousSample, m.currentSample, 1)
}


func cpuPercentages(s0, s1 *sigar.Cpu, numCPU int) Percentages {
if s0 == nil || s1 == nil {
return Percentages{}
}

// timeDelta is the total amount of CPU time available across all CPU cores.
timeDelta := s1.Total() - s0.Total()
if timeDelta <= 0 {
return Percentages{}
}

calculatePct := func(v0, v1 uint64) float64 {
cpuDelta := int64(v1 - v0)
pct := float64(cpuDelta) / float64(timeDelta)
return Round(pct*float64(numCPU), 4)
}

calculateTotalPct := func() float64 {
// IOWait time is excluded from the total as per #7627.
idle := calculatePct(s0.Idle, s1.Idle) + calculatePct(s0.Wait, s1.Wait)
return Round(float64(numCPU)-idle, 4)
}

return Percentages{
User: calculatePct(s0.User, s1.User),
System: calculatePct(s0.Sys, s1.Sys),
Idle: calculatePct(s0.Idle, s1.Idle),
IOWait: calculatePct(s0.Wait, s1.Wait),
IRQ: calculatePct(s0.Irq, s1.Irq),
Nice: calculatePct(s0.Nice, s1.Nice),
SoftIRQ: calculatePct(s0.SoftIrq, s1.SoftIrq),
Steal: calculatePct(s0.Stolen, s1.Stolen),
Total: calculateTotalPct(),
}
}


func Round(val float64, precision int64) (newVal float64) {
var round float64
pow := math.Pow(10, float64(precision))
digit := pow * val
_, div := math.Modf(digit)
if div >= 0.5 {
round = math.Ceil(digit)
} else {
round = math.Floor(digit)
}
newVal = round / pow
return
}
上一篇:js变量的声明带var与不带的区别
下一篇:没有了
网友评论