...

Source file src/internal/sysinfo/cpuinfo_linux.go

Documentation: internal/sysinfo

     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  		key, value, found := strings.Cut(scanner.Text(), ": ")
    44  		if !found {
    45  			continue
    46  		}
    47  		switch strings.TrimSpace(key) {
    48  		case "Model Name", "model name":
    49  			modelName = value
    50  		case "CPU MHz", "cpu MHz":
    51  			cpuMHz = value
    52  		}
    53  	}
    54  
    55  	if modelName == "" {
    56  		return ""
    57  	}
    58  
    59  	if cpuMHz == "" {
    60  		return modelName
    61  	}
    62  
    63  	// The modelName field already contains the frequency information,
    64  	// so the cpuMHz field information is not needed.
    65  	// modelName filed example:
    66  	//	Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz
    67  	f := [...]string{"GHz", "MHz"}
    68  	for _, v := range f {
    69  		if strings.Contains(modelName, v) {
    70  			return modelName
    71  		}
    72  	}
    73  
    74  	return modelName + " @ " + cpuMHz + "MHz"
    75  }
    76  

View as plain text