如何在GO中获得总内存/ RAM?

Usm*_*ail 11 go

如何获取Go中系统附加的内存/ RAM总量?我想尽可能使用本机代码.我找到了一个包装linux sysinfo命令的库.有更优雅的方式吗?

Ped*_*ito 10

除了runtime.MemStats,您还可以使用gosigar来监视系统内存.

  • `runtime.MemStats` 不提供系统内存,仅提供当前进程使用的各种内存。 (4认同)

小智 7

cgo和linux解决方案

package main

// #include <unistd.h>
import "C"

func main() {
    println(C.sysconf(C._SC_PHYS_PAGES)*C.sysconf(C._SC_PAGE_SIZE), " bytes")
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我没记错的话,c in go非常慢。我对吗? (2认同)
  • @kabanek系统内存大概不会经常改变,调用它一次并缓存它 (2认同)

Vol*_*ozo 5

您可以直接在 Go 程序中读取/proc/meminfo文件,正如 @Intermerne 所建议的。例如,您有以下结构:

type Memory struct {
    MemTotal     int
    MemFree      int
    MemAvailable int
}
Run Code Online (Sandbox Code Playgroud)

您可以从/proc/meminfo填充结构:

func ReadMemoryStats() Memory {
    file, err := os.Open("/proc/meminfo")
    if err != nil {
        panic(err)
    }
    defer file.Close()
    bufio.NewScanner(file)
    scanner := bufio.NewScanner(file)
    res := Memory{}
    for scanner.Scan() {
        key, value := parseLine(scanner.Text())
        switch key {
        case "MemTotal":
            res.MemTotal = value
        case "MemFree":
            res.MemFree = value
        case "MemAvailable":
            res.MemAvailable = value
        }
    }
    return res
}
Run Code Online (Sandbox Code Playgroud)

这是解析单独行的代码(但我认为它可以更有效地完成):

func parseLine(raw string) (key string, value int) {
    fmt.Println(raw)
    text := strings.ReplaceAll(raw[:len(raw)-2], " ", "")
    keyValue := strings.Split(text, ":")
    return keyValue[0], toInt(keyValue[1])
}

func toInt(raw string) int {
    if raw == "" {
        return 0
    }
    res, err := strconv.Atoi(raw)
    if err != nil {
        panic(err)
    }
    return res
}
Run Code Online (Sandbox Code Playgroud)

有关“/proc/meminfo”的更多信息,您可以从文档中阅读