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、运行结果

 

 

  

posted @ 2021-08-12 16:41  zhaogaojian  阅读(545)  评论(0编辑  收藏  举报