简介

psutil是一个跨平台进程和系统监控的Python库,而gopsutil是其Go语言版本的实现。

Go语言部署简单、性能好的特点非常适合做一些诸如采集系统信息和监控的服务,本文介绍的gopsutil库是知名Python库:psutil的一个Go语言版本的实现。

特点

gopsutils为我们屏蔽了各个系统之间的差异, 具有非常强悍的可移植性, 有了gopsutil, 我们不再需要针对不同的系统使用syscall调用对应的系统方法, 更棒的是gopsutil的实现中没有任何cgo的代码, 使得交叉编译成为可能.

安装

go get github.com/shirou/gopsutil

功能

gopsutil将不同的功能划分到不同的子包中

/*
cpu: CPU相关
disk: 磁盘相关
docker: docker相关
host: 主机相关
mem: 内存相关
net: 网络相关
process: 进程相关
*/

CPU

采集CPU相关信息

package main

import (
"fmt"
"github.com/shirou/gopsutil/cpu"
"time"
) // cpu info
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)
}
// CPU使用率
for {
percent, _ := cpu.Percent(time.Second, false)
fmt.Printf("cpu percent:%v\n", percent)
}
} func main() {
getCpuInfo()
} go run ps.go
{"cpu":0,"vendorId":"GenuineIntel","family":"6","model":"142","stepping":10,"physicalId":"","coreId":"","cores":4,"modelName":"Intel(R) Core(TM) i5-8257U CPU @ 1.40GHz","mhz":1400,"cacheSize":256,"flags":["fpu","vme","de","pse","tsc","msr","pae","mce","cx8","apic","sep","mtrr","pge","mca","cmov","pat","pse36","clfsh","ds","acpi","mmx","fxsr","sse","sse2","ss","htt","tm","pbe","sse3","pclmulqdq","dtes64","mon","dscpl","vmx","est","tm2","ssse3","fma","cx16","tpr","pdcm","sse4.1","sse4.2","x2apic","movbe","popcnt","aes","pcid","xsave","osxsave","seglim64","tsctmr","avx1.0","rdrand","f16c","rdwrfsgs","tsc_thread_offset","sgx","bmi1","avx2","smep","bmi2","erms","invpcid","fpu_csds","mpx","rdseed","adx","smap","clfsopt","ipt","mdclear","tsxfa","ibrs","stibp","l1df","ssbd","syscall","xd","1gbpage","em64t","lahf","lzcnt","prefetchw","rdtscp","tsci"],"microcode":""}
cpu percent:[10.099750623570355]
cpu percent:[7.615480649005255]

获取CPU负载消息

package main

import (
"fmt"
"github.com/shirou/gopsutil/load"
) func getCpuLoad() {
info, _ := load.Avg()
fmt.Printf("%v\n",info)
} func main() {
getCpuLoad()
} go run ps.go
{"load1":2.591796875,"load5":2.86572265625,"load15":2.7578125}

**

Memory

package main

import (
"fmt"
"github.com/shirou/gopsutil/mem"
) func getMemInfo() {
memInfo, _ := mem.VirtualMemory()
fmt.Printf("mem info:%v\n",memInfo)
} func main() {
getMemInfo()
} go run ps.go
mem info:{"total":8589934592,"available":1984147456,"used":6605787136,"usedPercent":76.9014835357666,"free":122396672,"active":1884549120,"inactive":1861750784,"wired":2657144832,"laundry":0,"buffers":0,"cached":0,"writeback":0,"dirty":0,"writebacktmp":0,"shared":0,"slab":0,"sreclaimable":0,"sunreclaim":0,"pagetables":0,"swapcached":0,"commitlimit":0,"committedas":0,"hightotal":0,"highfree":0,"lowtotal":0,"lowfree":0,"swaptotal":0,"swapfree":0,"mapped":0,"vmalloctotal":0,"vmallocused":0,"vmallocchunk":0,"hugepagestotal":0,"hugepagesfree":0,"hugepagesize":0}

Host

package main

import (
"fmt"
"github.com/shirou/gopsutil/host"
) func getHostInfo() {
hInfo, _ := host.Info()
fmt.Printf("host info:%v uptime:%v boottime:%v\n", hInfo, hInfo.Uptime, hInfo.BootTime)
} func main() {
getHostInfo()
} go run ps.go
host info:{"hostname":"youmendeMacBook-Pro.local","uptime":314216,"bootTime":1609206164,"procs":525,"os":"darwin","platform":"darwin","platformFamily":"Standalone Workstation","platformVersion":"11.1","kernelVersion":"20.2.0","kernelArch":"x86_64","virtualizationSystem":"","virtualizationRole":"","hostid":"82e2050c-5936-3d24-ad3b-ec4ec5c09e11"} uptime:314216 boottime:1609206164

Disk

package main

import (
"fmt"
"github.com/shirou/gopsutil/disk"
) // disk info
func getDiskInfo() {
parts, err := disk.Partitions(true)
if err != nil {
fmt.Printf("get Partitions failed, err:%v\n", err)
return
}
for _, part := range parts {
fmt.Printf("part:%v\n", part.String())
diskInfo, _ := disk.Usage(part.Mountpoint)
fmt.Printf("disk info:used:%v free:%v\n", diskInfo.UsedPercent, diskInfo.Free)
} ioStat, _ := disk.IOCounters()
for k, v := range ioStat {
fmt.Printf("%v:%v\n", k, v)
}
} func main() {
getDiskInfo()
} go run ps.go
part:{"device":"/dev/disk1s2s1","mountpoint":"/","fstype":"apfs","opts":"ro,journaled,multilabel"}
disk info:used:21.590916437596942 free:54644285440
part:{"device":"devfs","mountpoint":"/dev","fstype":"devfs","opts":"rw,nobrowse,multilabel"}
disk info:used:100 free:0
part:{"device":"/dev/disk1s5","mountpoint":"/System/Volumes/VM","fstype":"apfs","opts":"rw,noexec,nobrowse,journaled,multilabel,noatime"}
disk info:used:3.781419239013729 free:54644285440
part:{"device":"/dev/disk1s3","mountpoint":"/System/Volumes/Preboot","fstype":"apfs","opts":"rw,nobrowse,journaled,multilabel"}
disk info:used:0.5894192171529189 free:54644285440
part:{"device":"/dev/disk1s6","mountpoint":"/System/Volumes/Update","fstype":"apfs","opts":"rw,nobrowse,journaled,multilabel"}
disk info:used:0.0014916323547500506 free:54644285440
part:{"device":"/dev/disk1s1","mountpoint":"/System/Volumes/Data","fstype":"apfs","opts":"rw,nobrowse,journaled,multilabel"}
disk info:used:76.48839834497826 free:54644285440
part:{"device":"map auto_home","mountpoint":"/System/Volumes/Data/home","fstype":"autofs","opts":"rw,nobrowse,automounted,multilabel"}
disk info:used:0 free:0
disk0:{"readCount":7171236,"mergedReadCount":0,"writeCount":3480390,"mergedWriteCount":0,"readBytes":157156835328,"writeBytes":130453229568,"readTime":6791329,"writeTime":2234950,"iopsInProgress":0,"ioTime":9026279,"weightedIO":0,"name":"disk0","serialNumber":"","label":""}

IO

package main

import (
"fmt"
"github.com/shirou/gopsutil/net"
) func getNetInfo() {
info, _ := net.IOCounters(true)
for index, v := range info {
fmt.Printf("%v:%v send:%v recv:%v\n", index, v, v.BytesSent, v.BytesRecv)
}
} func main() {
getNetInfo()
} go run ps.go
0:{"name":"lo0","bytesSent":121344185,"bytesRecv":121344185,"packetsSent":433070,"packetsRecv":433070,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:121344185 recv:121344185
1:{"name":"gif0","bytesSent":0,"bytesRecv":0,"packetsSent":0,"packetsRecv":0,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:0 recv:0
2:{"name":"stf0","bytesSent":0,"bytesRecv":0,"packetsSent":0,"packetsRecv":0,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:0 recv:0
3:{"name":"en3","bytesSent":14748522,"bytesRecv":8111958,"packetsSent":61122,"packetsRecv":61250,"errin":0,"errout":1394,"dropin":0,"dropout":369,"fifoin":0,"fifoout":0} send:14748522 recv:8111958
4:{"name":"ap1","bytesSent":0,"bytesRecv":0,"packetsSent":0,"packetsRecv":0,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:0 recv:0
5:{"name":"en0","bytesSent":2744132038,"bytesRecv":12672282198,"packetsSent":7843906,"packetsRecv":9697152,"errin":0,"errout":1194,"dropin":0,"dropout":666,"fifoin":0,"fifoout":0} send:2744132038 recv:12672282198
6:{"name":"en1","bytesSent":0,"bytesRecv":0,"packetsSent":0,"packetsRecv":0,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:0 recv:0
7:{"name":"en2","bytesSent":0,"bytesRecv":0,"packetsSent":0,"packetsRecv":0,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:0 recv:0
8:{"name":"awdl0","bytesSent":241402,"bytesRecv":0,"packetsSent":1961,"packetsRecv":0,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:241402 recv:0
9:{"name":"llw0","bytesSent":0,"bytesRecv":0,"packetsSent":0,"packetsRecv":0,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:0 recv:0
10:{"name":"utun0","bytesSent":187730,"bytesRecv":0,"packetsSent":1629,"packetsRecv":0,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:187730 recv:0
11:{"name":"utun1","bytesSent":187730,"bytesRecv":0,"packetsSent":1629,"packetsRecv":0,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:187730 recv:0
12:{"name":"en6","bytesSent":20906,"bytesRecv":6600,"packetsSent":149,"packetsRecv":60,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:20906 recv:6600
13:{"name":"en7","bytesSent":20906,"bytesRecv":6600,"packetsSent":149,"packetsRecv":60,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:20906 recv:6600
14:{"name":"bridg","bytesSent":0,"bytesRecv":0,"packetsSent":0,"packetsRecv":0,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:0 recv:0
15:{"name":"bridg","bytesSent":41812,"bytesRecv":12360,"packetsSent":298,"packetsRecv":120,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:41812 recv:12360
16:{"name":"bridg","bytesSent":41812,"bytesRecv":12360,"packetsSent":298,"packetsRecv":120,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0} send:41812 recv:12360

Go之获取系统性能指标 - goPsutil的更多相关文章

  1. ThinPHP命名空间,连接数据库是要修改的配置文件,Model数据模型层,跨控制器调用,如何获取系统常量信息,

    一.命名空间(主要是为了实现自动加载类) *命名空间(相当于虚拟的目录),为了让类有一个统一的文件夹来管理(可以自动加载'类'),每个文件都要有命名空间*tp如何做命名空间:*TP框架下有一个初始命名 ...

  2. Delphi编程获取系统当前进程、窗口句柄、文件属性以(转)

    Delphi编程获取系统当前进程.窗口句柄.文件属性以及程序运行状态. uses TLHelp32,PsAPI; (1)显示进程列表:procedure TForm1.Button2Click(Sen ...

  3. android 获取系统联系人 完全解析

    一.代码 1.ContactsEngine.java import java.util.ArrayList; import java.util.HashMap; import java.util.Li ...

  4. Android获取系统时间方法的总结

    Android获取系统时间方法的方法有很多种,常用的有Calendar.Date.currentTimeMills等方法. (1)Calendar Calendar获取系统时间首先要用Calendar ...

  5. Android 获取系统的联系人

    本文主要介绍android中怎样获取系统的联系人数据 首先打开模拟器 点击联系人图标按钮 说明系统联系人数据库是空的,打开File explorer,找到data/data下面的文件夹: 将conta ...

  6. Linux sysinfo获取系统相关信息

    Linux中,可以用sysinfo来获取系统相关信息. #include <stdio.h> #include <stdlib.h> #include <errno.h& ...

  7. android获取系统通讯录

    package com.example.administrator.yunphone.View; import android.app.Fragment; import android.databas ...

  8. Android如何通过shareduserid获取系统权限

    [原文] android会为每个apk进程分配一个单独的空间(比如只能访问/data/data/自己包名下面的文件),一般情况下apk之间是禁止相互访问数据的.通过Shared User id,拥有同 ...

  9. 用PHP获取系统时间时,时间比当前时间少8个小时

    自PHP5.0开始,用PHP获取系统时间时,时间比当前时间少8个小时.原因是PHP.ini中没有设置timezone时,PHP是使用的UTC时间,所以在中国时间要少8小时. 解决办法: 1.在PHP. ...

随机推荐

  1. SpringBoot系列:六、集成Swagger文档

    本篇开始介绍Api文档Swagger的集成 一.引入maven依赖 <dependency> <groupId>io.springfox</groupId> < ...

  2. 学习abp vnext框架到精简到我的Vop框架

    学习目标 框架特点 基于.NET 5平台开发 模块化系统 极少依赖 极易扩展 ....... 框架目的 学习.NET 5平台 学习abp vnext 上图大部分功能已经实现,多数是参考(copy)ab ...

  3. 第4.3节 Python中与迭代相关的函数

    下面要介绍的enumerate.range.zip.reversed.sorted属于Python内置的函数或者类别,返回的对象都可通过迭代方法访问. 一.    enumerate函数 1.     ...

  4. 第15.25节 PyQt(Python+Qt)入门学习:Model/View开发实战--使用QTableView展示Excel文件内容

    老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 一.概述 在前面的订阅专栏<第十九章.Model/View开发:QTableView的功能及属 ...

  5. 安恒2018年三月月赛MISC蜘蛛侠呀

    到处都是知识盲区hhh 下载了out.pcap之后,里面有很多ICMP包 看到ttl之后联想到西湖论剑里面的一道杂项题,无果 看WP知道可以使用wireshark的tshark命令提取流量包里面的文件 ...

  6. Mysql 逻辑架构图及日志系统

    我们经常能看到如下的逻辑架构图,但是往往不能进行很好的记忆,看过就忘记了,也不知道它的实现方式.今天通过简单的画图来简单了解一下mysql到底是如何执行一个select语句,如何update一条语句. ...

  7. [SQL Server]多次为 '派生表' 指定了列 'id'

    问题: 原因: 因为派生表oo中出现了两个同样的'ID'属性,所以会报[多次为 'o' 指定了列 'ID']的错误. 只需要把第二个星号替换成所需要的列名并把重复字段重命名就好了 解决方案:

  8. 个人项目作业——wc.exe

    一.Github项目地址 https://github.com/PIPIYing/wc 二.项目概况 项目描述 Word Count 1. 实现一个简单而完整的软件工具(源程序特征统计程序). 2. ...

  9. MySQL必知必会详细总结

    一.检索数据 1.检索单个列:SELECT prod_name FROM products; 2.检索多个列:SELECT prod_id,prod_name,prod_price FROM prod ...

  10. LibreOj-10012-「一本通-1-2-例-2」Best-Cow-Fences

    题目地址 思路 二分平均值,区间为$0$~$2000$.将每个$a[i]$减去平均值,就只用考虑字段和是否$>=0$了. 关于计算子段和,可以使用前缀和表示,$sum[i]$表示前$i$个数的和 ...