cpuinfo_linux.mx raw
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package sysinfo
6
7 import (
8 "bufio"
9 "bytes"
10 "io"
11 "os"
12 )
13
14 func readLinuxProcCPUInfo(buf []byte) error {
15 f, err := os.Open("/proc/cpuinfo")
16 if err != nil {
17 return err
18 }
19 defer f.Close()
20
21 _, err = io.ReadFull(f, buf)
22 if err != nil && err != io.ErrUnexpectedEOF {
23 return err
24 }
25
26 return nil
27 }
28
29 func osCPUInfoName() []byte {
30 modelName := ""
31 cpuMHz := ""
32
33 // The 512-byte buffer is enough to hold the contents of CPU0
34 buf := []byte{:512}
35 err := readLinuxProcCPUInfo(buf)
36 if err != nil {
37 return ""
38 }
39
40 scanner := bufio.NewScanner(bytes.NewReader(buf))
41 for scanner.Scan() {
42 key, value, found := bytes.Cut(scanner.Text(), ": ")
43 if !found {
44 continue
45 }
46 switch bytes.TrimSpace(key) {
47 case "Model Name", "model name":
48 modelName = value
49 case "CPU MHz", "cpu MHz":
50 cpuMHz = value
51 }
52 }
53
54 if modelName == "" {
55 return ""
56 }
57
58 if cpuMHz == "" {
59 return modelName
60 }
61
62 // The modelName field already contains the frequency information,
63 // so the cpuMHz field information is not needed.
64 // modelName filed example:
65 // Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz
66 f := [...][]byte{"GHz", "MHz"}
67 for _, v := range f {
68 if bytes.Contains(modelName, v) {
69 return modelName
70 }
71 }
72
73 return modelName + " @ " + cpuMHz + "MHz"
74 }
75