Go入门笔记-11 Go 获取Linux系统CPU占用率

EdgeX支持多种平台下测试CPU占用率,下面是Linux核心代码

1、代码

package main

import (
	"bitbucket.org/bertimus9/systemstat"
	"fmt"
	"math"
	"time"
)

var lastSample CpuUsage
var usageAvg float64

type CpuUsage struct {
	Busy, // time used by all processes. this ideally does not include system processes.
	Idle, // time used by the idle process
	Total uint64 // reported sum total of all usage
}

func PollCpu() (cpuSnapshot CpuUsage) {
	linuxSample := systemstat.GetCPUSample()
	return CpuUsage{
		Busy:  linuxSample.Nice + linuxSample.User,
		Idle:  linuxSample.Idle,
		Total: linuxSample.Total,
	}
}

func AvgCpuUsage(init, final CpuUsage) (avg float64) {
	// SimpleAverage only uses idle and total, so only copy those
	linuxInit := systemstat.CPUSample{
		Idle:  init.Idle,
		Total: init.Total,
	}

	linuxFinal := systemstat.CPUSample{
		Idle:  final.Idle,
		Total: final.Total,
	}

	avg = systemstat.GetSimpleCPUAverage(linuxInit, linuxFinal).BusyPct

	if avg < .000001 || math.IsNaN(avg) {
		return 0.0
	}

	return avg
}
func cpuUsageAverage() {
	nextUsage := PollCpu()
	usageAvg = AvgCpuUsage(lastSample, nextUsage)
	lastSample = nextUsage
	//打印输出读到的信息
	fmt.Println(usageAvg)

}
func main() {

	for {

		cpuUsageAverage()
		fmt.Println(time.Second)
		time.Sleep(time.Duration(2) * time.Second) //
	}

	return
}

2、运行结果

  

本博客是个人工作中记录,遇到问题可以互相探讨,没有遇到的问题可能没有时间去特意研究,勿扰。
另外建了几个QQ技术群:
2、全栈技术群:616945527,加群口令abc123
2、硬件嵌入式开发: 75764412
3、Go语言交流群:9924600

闲置域名www.nsxz.com出售(等宽等高字符四字域名)。
原文地址:https://www.cnblogs.com/zhaogaojian/p/15133478.html