drfkl66684 2016-02-24 00:36
浏览 270

返回Golang中的CPU插槽,内核和线程数

Using Golang I'm trying to find/write a function that would return the number of CPU Sockets, Cores per socket, and Threads per core a Linux system. For example, a server might have 2 CPUs each with 4 cores, with hyperthreading, it could handle 8 threads per CPU.

Sample Output:

{
  "CPUSockets": "2",
  "CoresPerSocket": "4",
  "ThreadsPerCore": "2"
}

Question: Do you know of any Go Package or pseudo code that could provide this information?

Note: I've looked at various go implementations of psutil but I can't find one that returns the number of sockets or distinguishes between Cores and Threads. The data I want is very easily accessible by running lscpu but I don't know how to access that using Go.

  • 写回答

1条回答 默认 最新

  • duanju8308 2016-02-24 04:11
    关注

    I ended up figuring it out, see below:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "os/exec"
        "strconv"
        "strings"
    )
    
    type CPUInfo struct {
        Sockets        int32 `json:"sockets"`
        CoresPerSocket int32 `json:"cores_per_socket"`
        ThreadsPerCore int32 `json:"threads_per_core"`
    }
    
    func main() {
        out, _ := exec.Command("lscpu").Output()
        outstring := strings.TrimSpace(string(out))
        lines := strings.Split(outstring, "
    ")
        c := CPUInfo{}
    
        for _, line := range lines {
            fields := strings.Split(line, ":")
            if len(fields) < 2 {
                continue
            }
            key := strings.TrimSpace(fields[0])
            value := strings.TrimSpace(fields[1])
    
            switch key {
            case "Socket(s)":
                t, _ := strconv.Atoi(value)
                c.Sockets = int32(t)
            case "Core(s) per socket":
                t, _ := strconv.Atoi(value)
                c.CoresPerSocket = int32(t)
            case "Thread(s) per core":
                t, _ := strconv.Atoi(value)
                c.ThreadsPerCore = int32(t)
            }
        }
    
        CPUInfoJSON, _ := json.MarshalIndent(c, "", "  ")
        fmt.Println(string(CPUInfoJSON))
    }
    

    Output:

    tbenz9@ubuntu-dev: go run socket.go 
    {
      "sockets": 1,
      "cores_per_socket": 2,
      "threads_per_core": 2
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。