forked from zhufuyi/sponge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpu.go
94 lines (79 loc) · 2.17 KB
/
cpu.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Package cpu is a library that counts system and process cpu usage.
package cpu
import (
"fmt"
"os"
"strconv"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/process"
)
// System cpu information
type System struct {
UsagePercent float64 `json:"usage_percent"` // cpu usage, unit(%), current logical CPU usage, total usage is cores*UsagePercent
CPUInfo []CPUInfo `json:"cpu_info"`
}
// CPUInfo cpu information
type CPUInfo struct {
ModelName string `json:"modelName"`
Cores int32 `json:"cores"`
Frequency float64 `json:"frequency"` // cpu frequency, unit(Mhz)
}
// Process information
type Process struct {
UsagePercent float64 `json:"usage_percent"` // cpu usage, unit(%), current process occupies current logical CPU, total usage is cores*UsagePercent
RSS uint64 `json:"rss"` // use of physical memory, unit(M)
VMS uint64 `json:"vms"` // use of virtual memory, unit(M)
}
// GetSystemCPU get system cpu info
func GetSystemCPU() *System {
sysUsagePercent := 0.0
vs, err := cpu.Percent(0, false) // total cpu Percent
if err != nil {
fmt.Printf("cpu.Percent error, %v\n", err)
}
if len(vs) == 1 {
sysUsagePercent = vs[0] * 10
}
var cpuInfos []CPUInfo
cpus, err := cpu.Info()
if err != nil {
fmt.Printf("cpu.Info error, %v\n", err)
} else {
for _, v := range cpus {
cpuInfos = append(cpuInfos, CPUInfo{
ModelName: v.ModelName,
Cores: v.Cores,
Frequency: v.Mhz,
})
}
}
return &System{
UsagePercent: floatRound(sysUsagePercent, 1),
CPUInfo: cpuInfos,
}
}
// GetProcess get current process info
func GetProcess() *Process {
proc := &Process{}
currentPid := os.Getpid()
p, err := process.NewProcess(int32(currentPid))
if err != nil {
fmt.Printf("process.NewProcess error, %v\n", err)
return proc
}
percent, err := p.CPUPercent()
if err != nil {
fmt.Printf("p.CPUPercent error, %v\n", err)
return proc
}
proc.UsagePercent = floatRound(percent, 1)
mInfo, _ := p.MemoryInfo()
proc.RSS = mInfo.RSS >> 20
proc.VMS = mInfo.VMS >> 20
return proc
}
func floatRound(f float64, n int) float64 {
format := "%." + strconv.Itoa(n) + "f"
res, _ := strconv.ParseFloat(fmt.Sprintf(format, f), 64)
return res
}