扩展包:github.com/shirou/gopsutil,此项目是在https://github.com/giampaolo/psutil
的基础上,基于golang的实现。
go get github.com/shirou/gopsutil/v3
package mainimport ("fmt""github.com/shirou/gopsutil/v3/mem"
)func main() {v, _ := mem.VirtualMemory()// almost every return value is a structfmt.Printf("Total: %v, Free:%v, UsedPercent:%f%%\n", v.Total, v.Free, v.UsedPercent)// convert to JSON. String() is also implementedfmt.Println(v)
}
> go run gops.go
Total: 17083498496, Free:6954065920, UsedPercent:57.918910%
{"total":17083498496,"available":7154073600,"used":9894576128,"usedPercent":57.9189100541482,"free":6954065920,"active":171577344,"inactive":161665024,"wired":0,"laundry":0,"buffers":34848768,"cached":200007680,"writeBack":0,"dirty":0,"writeBackTmp":0,"shared":18145280,"slab":14200832,"sreclaimable":6905856,"sunreclaim":7294976,"pageTables":2584576,"swapCached":0,"commitLimit":527896576,"committedAS":3532865536,"highTotal":0,"highFree":0,"lowTotal":0,"lowFree":0,"swapTotal":51539607552,"swapFree":51288666112,"mapped":73117696,"vmallocTotal":125829120,"vmallocUsed":21807104,"vmallocChunk":67629056,"hugePagesTotal":0,"hugePagesFree":0,"hugePagesRsvd":0,"hugePagesSurp":0,"hugePageSize":2097152,"anonHugePages":2097152}
在 Linux 系统上,一切皆文件,所以对于操作系统的这些信息,都是可以通过读取对应的文件来得到。
比如以计算CPU使用率为例,我们一般使用top命令来展示,因此可以使用exec.Command
来调用top命令并解析返回的内容得到,也可以读取/proc/
目录下文件。
/proc/stat: 提供了内核统计数据,当然也包括了 CPU 的数据
/proc/cpuinfo: 提供了有关 CPU 的详细数据,包括 CPU 型号、核心数量等
/proc/<PID>/stat: 与 /proc/stat 提供的数据类似,但是数据对应的是单个进程
但是得到的都是元数据,至于CPU使用率该怎么计算还需要找找规则。
所以,还是使用psutil比较合适,毕竟里面的计算规则是大家公认的。