-
Notifications
You must be signed in to change notification settings - Fork 3
/
info_gopsutil.go
executable file
·52 lines (45 loc) · 1.12 KB
/
info_gopsutil.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
//go:build 386 || amd64 || arm || arm64
package cpuKit
import (
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/process"
"github.com/sirupsen/logrus"
"os"
"time"
)
func printBasicDetails(logger *logrus.Logger) {
if cpuPercent, err := GetUsagePercent(); err != nil {
logger.WithError(err).Warn("[CHIMERA, CPU] Fail to get cpu usage")
} else {
logger.Infof("[CHIMERA, CPU] usage percent: [%.2f]%%.", cpuPercent)
}
}
// GetUsagePercent CPU使用率
/*
PS: 耗时约1s.
e.g.
() => 12.701612903175233
*/
func GetUsagePercent() (float64, error) {
s, err := cpu.Percent(time.Second, false)
if err != nil {
return 0, err
}
return s[0], nil
}
// GetCurrentProcessUsagePercent 获取 当前进程 的CPU使用百分比.
/*
PS: 类似Linux命令: top -p ${pid}
*/
func GetCurrentProcessUsagePercent() (float64, error) {
var pid = int32(os.Getpid())
return GetProcessUsagePercent(pid)
}
// GetProcessUsagePercent 获取 指定进程 的CPU使用百分比.
func GetProcessUsagePercent(pid int32) (float64, error) {
p, err := process.NewProcess(pid)
if err != nil {
return 0, err
}
return p.CPUPercent()
}