• 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出售(等宽等高字符四字域名)。
  • 相关阅读:
    Headless MSBuild Support for SSDT (*.sqlproj) Projects
    dbDacFx Provider for Incremental Database publishing
    Cannot spawn... TortoisePlink
    Windows server 2012同时进行多个会话登陆的策略设置
    Workspace Cloning / Sharing in Jenkins
    How to change Jenkins default folder on Windows?
    使用Jenkins配置自动化构建
    Auto push git tag
    Azure Deploy
    sql server中index的REBUILD和REORGANIZE
  • 原文地址:https://www.cnblogs.com/zhaogaojian/p/15133478.html
Copyright © 2020-2023  润新知