【Golang】精进探索:利用gopsutil库高效获取服务器资源信息的进阶策略
大家好 我是寸铁👊
总结了一篇【Golang】精进探索:利用gopsutil库高效获取服务器资源信息的进阶策略的文章✨
喜欢的小伙伴可以点点关注 💝
前言
在现代计算机系统中,有效地监控和管理服务器资源是至关重要的。了解服务器的资源利用情况可以帮助我们优化性能、识别问题并做出及时的响应。而gopsutil
这个Go语言编写的库提供了一种便捷的方式来获取各种系统资源信息。本文将深入探讨如何利用gopsutil
库更高效地获取服务器资源信息,为您展示一些高级技巧和进阶策略。
获取CPU相关信息
cpu.Info()
返回cpu的具体信息
cpuInfo, _ := cpu.Info()
fmt.Println("返回cpu的具体信息:", cpuInfo)
返回信息如下: type InfoStat struct { CPU int32 //中央处理器 VendorID string //供应商 ID Family string //家庭 Model string //型号 Stepping int32 //步 进 PhysicalID string //物理 ID CoreID string //核心 ID Cores int32 //核心数 ModelName string //型号名称 Mhz float64 //兆赫 CacheSize int32 //缓存大小 Flags []string //标志 Microcode string //微码 }
cpu.Times()
CPU 执行不同操作所花费的时间 工作种类
cpuCounts, _ := cpu.Times(false)
fmt.Println("返回cpu执行不同操作所花费的时间和工作种类:", cpuCounts)
type TimesStat struct { CPU string //中央处理器 User float64 //用户 System float64 //系统 Idle float64 //闲置 Nice float64 //好 Iowait float64 //输入输出等待 Irq float64 //设备的中断请求 Softirq float64 //硬中断的服务程序”发起的对内核的中断 Steal float64 //偷(抢占) Guest float64 //“来宾帐户”。 GuestNice float64 //好的“来宾帐户”。 }
cpu.Percent()
返回cpu的使用率
cpuPercent, _ := cpu.Percent(time.Second, false)
fmt.Println("返回cpu的使用率:", cpuPercent)
CPUdemo
package main
import (
"fmt"
"github.com/shirou/gopsutil/cpu"
"time"
)
func main() {
cpuInfo, _ := cpu.Info()
fmt.Println("返回cpu的具体信息:", cpuInfo)
fmt.Println()
cpuCounts, _ := cpu.Times(false)
fmt.Println("返回cpu执行不同操作所花费的时间 工作种类:", cpuCounts)
//TimesStat 包含 CPU 执行不同操作所花费的时间 工作种类。时间单位以秒为单位。它基于 linux /proc/stat 文件。
fmt.Println()
cpuPercent, _ := cpu.Percent(time.Second, false