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

时间:2016-02-24 00:36:21

标签: go psutil

使用Golang我正在尝试查找/编写一个函数,该函数将返回Linux系统的CPU套接字数,每个插槽的内核数和每个内核的线程数。例如,服务器可能有2个CPU,每个CPU有4个内核,超线程,每个CPU可以处理8个线程。

示例输出:

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

问题:您知道可以提供此信息的任何Go Package或伪代码吗?

注意:我已经查看了psutil的各种go实现,但我找不到一个返回套接字数量或区分内核和线程的实现。运行lscpu可以非常方便地访问我想要的数据,但我不知道如何使用Go访问它。

1 个答案:

答案 0 :(得分:1)

我最终搞清楚了,见下文:

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, "\n")
    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))
}

输出:

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