-
Notifications
You must be signed in to change notification settings - Fork 94
/
cpu.go
85 lines (75 loc) · 2.01 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
// Copyright © 2016 Zlatko Čalušić
//
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
package sysinfo
import (
"bufio"
"fmt"
"os"
"regexp"
"runtime"
"strconv"
"strings"
)
// CPU information.
type CPU struct {
Vendor string `json:"vendor,omitempty"`
Model string `json:"model,omitempty"`
Speed uint `json:"speed,omitempty"` // CPU clock rate in MHz
Cache uint `json:"cache,omitempty"` // CPU cache size in KB
Cpus uint `json:"cpus,omitempty"` // number of physical CPUs
Cores uint `json:"cores,omitempty"` // number of physical CPU cores
Threads uint `json:"threads,omitempty"` // number of logical (HT) CPU cores
}
var (
reTwoColumns = regexp.MustCompile("\t+: ")
reExtraSpace = regexp.MustCompile(" +")
reCacheSize = regexp.MustCompile(`^(\d+) KB$`)
)
func (si *SysInfo) getCPUInfo() {
si.CPU.Threads = uint(runtime.NumCPU())
f, err := os.Open("/proc/cpuinfo")
if err != nil {
return
}
defer f.Close()
cpu := make(map[string]bool)
core := make(map[string]bool)
var cpuID string
s := bufio.NewScanner(f)
for s.Scan() {
if sl := reTwoColumns.Split(s.Text(), 2); sl != nil {
switch sl[0] {
case "physical id":
cpuID = sl[1]
cpu[cpuID] = true
case "core id":
coreID := fmt.Sprintf("%s/%s", cpuID, sl[1])
core[coreID] = true
case "vendor_id":
if si.CPU.Vendor == "" {
si.CPU.Vendor = sl[1]
}
case "model name":
if si.CPU.Model == "" {
// CPU model, as reported by /proc/cpuinfo, can be a bit ugly. Clean up...
model := reExtraSpace.ReplaceAllLiteralString(sl[1], " ")
si.CPU.Model = strings.Replace(model, "- ", "-", 1)
}
case "cache size":
if si.CPU.Cache == 0 {
if m := reCacheSize.FindStringSubmatch(sl[1]); m != nil {
if cache, err := strconv.ParseUint(m[1], 10, 64); err == nil {
si.CPU.Cache = uint(cache)
}
}
}
}
}
}
if s.Err() != nil {
return
}
si.CPU.Cpus = uint(len(cpu))
si.CPU.Cores = uint(len(core))
}