1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
info.go 2.85 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-07-22 01:28 . monitor
package system
import (
"fmt"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/disk"
"github.com/shirou/gopsutil/v3/mem"
)
func Info() string {
d := Disk()
m := Mem()
return SIToString(&d, &m, CpuPercent())
}
func SIToString(d *DiskPath, m *MemInfo, cpuPercent float64) string {
in := fmt.Sprintf("Cpu=> UsedPercent: %.2f\r\n"+
"Memory=> Total: %v, Available: %v, Used: %v, UsedPercent: %.2f\r\n"+
"Disk=> Path: %v, Total: %v, Free: %v, Used: %v, UsedPercent: %.2f\r\n",
cpuPercent,
m.Total, m.Available, m.Used, m.UsedPercent,
d.Path, d.Total, d.Free, d.Used, d.UsedPercent)
return in
}
const GB = 1024 * 1024 * 1024
func Mem() MemInfo {
v, er := mem.VirtualMemory()
if er != nil {
return MemInfo{}
}
return MemInfo{
Total: v.Total / GB,
Available: v.Available / GB,
Used: v.Used / GB,
UsedPercent: v.UsedPercent,
}
}
type MemInfo struct {
// Total amount of RAM on this system
Total uint64 `json:"total"`
// RAM available for programs to allocate
//
// This value is computed from the kernel specific values.
Available uint64 `json:"available"`
// RAM used by programs
//
// This value is computed from the kernel specific values.
Used uint64 `json:"used"`
// Percentage of RAM used by programs
//
// This value is computed from the kernel specific values.
UsedPercent float64 `json:"usedPercent"`
}
func CpuPercent() float64 {
in, er := cpu.Percent(0, false)
if er != nil {
return 0
}
return in[0]
}
func Cpu() CpuInfo {
in, er := cpu.Times(false) //(0*time.Second, false)
if er != nil {
return CpuInfo{}
}
var inf CpuInfo
for i := range in {
inf.User = in[i].User
inf.System = in[i].System
inf.Idle = in[i].Idle
inf.Nice = in[i].Nice
}
return inf
}
type CpuInfo struct {
User float64 `json:"user"`
System float64 `json:"system"`
Idle float64 `json:"idle"`
Nice float64 `json:"nice"`
}
func Disk() DiskPath {
return DiskWithPath("/")
}
func DiskWithPath(path string) DiskPath {
d, err := disk.Usage(path)
if err != nil {
return DiskPath{}
}
return DiskPath{
Path: d.Path,
Total: d.Total / GB,
Free: d.Free / GB,
Used: d.Used / GB,
UsedPercent: d.UsedPercent,
}
}
func DiskAll() []DiskPath {
var paths []DiskPath
part, er := disk.Partitions(false)
if er != nil {
return paths
}
for i := range part {
if d, err := disk.Usage(part[i].Mountpoint); err == nil {
var dp = DiskPath{
Path: d.Path,
Total: d.Total / GB,
Free: d.Free / GB,
Used: d.Used / GB,
UsedPercent: d.UsedPercent,
}
if dp.Total > 0 {
paths = append(paths, dp)
}
}
}
return paths
}
type DiskPath struct {
Path string `json:"path,omitempty"`
Total uint64 `json:"total"`
Free uint64 `json:"free"`
Used uint64 `json:"used"`
UsedPercent float64 `json:"usedPercent"`
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.90

搜索帮助