简介

psutil 是一个使用 Python 编写的跨平台平台进程和系统利用率监控库,gopsutil 就是 psutil 的 go 语言实现。

使用

安装

go get github.com/shirou/gopsutil/v3

CPU

获取cpu基本信息

func getCpuInfo() {
	cpuInfos, err := cpu.Info()
	if err != nil {
		fmt.Printf("get cpu info failed, err:%v", err)
	}
	for _, ci := range cpuInfos {
		fmt.Println(ci)
	}
	for {
		percent, _ := cpu.Percent(time.Second, false)
		fmt.Printf("cpu percent:%v\n", percent)
	}
}
{"cpu":0,"vendorId":"GenuineIntel","family":"205","model":"","stepping":0,"physicalId":"BFEBFBFF000406E3","coreId":"","cores":4,"modelName":"Intel(R)
 Core(TM) i5-6200U CPU @ 2.30GHz","mhz":2400,"cacheSize":0,"flags":[],"microcode":""}
cpu percent:[40.625]
cpu percent:[15]
cpu percent:[9.615384615384617]
cpu percent:[28.125]

获取cpu负载

func getCpuLoad() {
    info, err := load.Avg()
    if err != nil {
    panic(err)
    }
    fmt.Printf("%v\n", info)
}

内存

获取内存

func getMemInfo() {
	memInfo, _ := mem.VirtualMemory()
	fmt.Printf("mem info:%v\n", memInfo)
}
mem info:{"total":8472920064,"available":1921372160,"used":6551547904,"usedPerce
nt":77,"free":1921372160,"active":0,"inactive":0,"wired":0,"laundry":0,"buffers"
:0,"cached":0,"writeBack":0,"dirty":0,"writeBackTmp":0,"shared":0,"slab":0,"srec
laimable":0,"sunreclaim":0,"pageTables":0,"swapCached":0,"commitLimit":0,"commit
tedAS":0,"highTotal":0,"highFree":0,"lowTotal":0,"lowFree":0,"swapTotal":0,"swap
Free":0,"mapped":0,"vmallocTotal":0,"vmallocUsed":0,"vmallocChunk":0,"hugePagesT
otal":0,"hugePagesFree":0,"hugePagesRsvd":0,"hugePagesSurp":0,"hugePageSize":0}

库的其他用法可以查看相应的官方文档。

小结

本文主要介绍 gopsutil 的使用,使用 gopsutil 可以很好的监控系统的资源。 从 github 仓库可以看到此库十分受欢迎,在许多开源项目中有使用。

本文的相关代码在这: https://github.com/overstarry/psutil/tree/master

参考