获取 linux 的 CPU 使用率

linux CPU 用量保存在 /proc/stat 文件里。
4.4 内核已经拓展到十元组,通过

1
man proc

可以知道分别时是 user nice system idle iowait irq softirq steal guest guest_nice

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
package main

import (
"encoding/binary"
"fmt"
"os"
"time"
)

var fstat *os.File

func getcpuusage() (int, int) {
fd := fstat
if fd == nil {
var err error
fd, err = os.Open("/proc/stat")
if err != nil {
return -1, -1
}
fstat = fd
}
var stat [128]byte
fd.Seek(0, os.SEEK_SET)
n, err := fd.Read(stat[:])
if fd != fstat {
fd.Close()
}
if err != nil || binary.LittleEndian.Uint32(stat[:4]) != 0x20757063 {
return -1, -1
}
total := 0
idle := 0
usage := 0
idx := 0
ok := false
eol := false
for i := 4; i < n; i++ {
c := stat[i]
if c == '\n' {
total += usage
eol = true
break
}
if '0' <= c && c <= '9' {
usage *= 10
usage += int(c) - '0'
ok = true
} else if ok {
total += usage
if idx == 3 {
idle = usage
}
usage = 0
idx++
ok = false
}
}
if !eol {
return -1, -1
}
return total, idle
}

func main() {
prevtotal, previdle := 0, 0
for {
total, idle := getcpuusage()
usage := 100 - 100*(idle-previdle)/(total-prevtotal+1)
fmt.Println(usage)
prevtotal, previdle = total, idle
time.Sleep(time.Second)
}
}