github.com/bir3/gocompiler@v0.9.2202/src/internal/sysinfo/cpuinfo_linux.go (about) 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 "strings" 13 ) 14 15 func readLinuxProcCPUInfo(buf []byte) error { 16 f, err := os.Open("/proc/cpuinfo") 17 if err != nil { 18 return err 19 } 20 defer f.Close() 21 22 _, err = io.ReadFull(f, buf) 23 if err != nil && err != io.ErrUnexpectedEOF { 24 return err 25 } 26 27 return nil 28 } 29 30 func osCpuInfoName() string { 31 modelName := "" 32 cpuMHz := "" 33 34 // The 512-byte buffer is enough to hold the contents of CPU0 35 buf := make([]byte, 512) 36 err := readLinuxProcCPUInfo(buf) 37 if err != nil { 38 return "" 39 } 40 41 scanner := bufio.NewScanner(bytes.NewReader(buf)) 42 for scanner.Scan() { 43 line := scanner.Text() 44 if !strings.Contains(line, ":") { 45 continue 46 } 47 48 field := strings.SplitN(line, ": ", 2) 49 switch strings.TrimSpace(field[0]) { 50 case "Model Name", "model name": 51 modelName = field[1] 52 case "CPU MHz", "cpu MHz": 53 cpuMHz = field[1] 54 } 55 } 56 57 if modelName == "" { 58 return "" 59 } 60 61 if cpuMHz == "" { 62 return modelName 63 } 64 65 // The modelName field already contains the frequency information, 66 // so the cpuMHz field information is not needed. 67 // modelName filed example: 68 // Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz 69 f := [...]string{"GHz", "MHz"} 70 for _, v := range f { 71 if strings.Contains(modelName, v) { 72 return modelName 73 } 74 } 75 76 return modelName + " @ " + cpuMHz + "MHz" 77 }