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

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
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值