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
2、硬件嵌入式开发: 75764412
3、Go语言交流群:9924600
闲置域名WWW.EXAI.CN (超级人工智能)出售。
另外建了几个QQ技术群:
2、全栈技术群:616945527
2、硬件嵌入式开发: 75764412
3、Go语言交流群:9924600
闲置域名WWW.EXAI.CN (超级人工智能)出售。

浙公网安备 33010602011771号