如何从 Mac 上的 Golang 代码获取总 RAM?

Sim*_*Que 1 macos go sysinfo

我在 golang 中有一些 Linux 代码:

import "syscall"

var info syscall.Sysinfo_t
err := syscall.Sysinfo(&info)
totalRam := info.Totalram
Run Code Online (Sandbox Code Playgroud)

我想将其移植到 Mac OS X。我看到 Sysinfo 在 Linux 上可用,但在 Mac 上不可用:

Linux:

$ go list -f '{{.GoFiles}}' syscall | sed -e "s/[][]//g" | xargs fgrep --color -Iwn Sysinfo
syscall_linux.go:962://sysnb    Sysinfo(info *Sysinfo_t) (err error)
zsyscall_linux_amd64.go:822:func Sysinfo(info *Sysinfo_t) (err error) {\
Run Code Online (Sandbox Code Playgroud)

苹果电脑:

$ go list -f '{{.GoFiles}}' syscall | sed -e "s/[][]//g" | xargs fgrep --color -Iwn Sysinfo
# No results
Run Code Online (Sandbox Code Playgroud)

在 Mac 上获取系统 RAM 信息的正确方法是什么?

p9s*_*9sh 5

此代码支持交叉编译。

先决条件

获取这个包github.com/shirou/gopsutil/mem

package main

import (
    "fmt"
    "log"
    "os"
    "runtime"
    "strconv"

    "github.com/shirou/gopsutil/mem"
)

func errHandler(err error) {
    if err != nil {
        log.Println(err.Error())
        os.Exit(1)
    }
}

func main() {
    runtimeOS := runtime.GOOS
    runtimeARCH := runtime.GOARCH
    fmt.Println("OS: ", runtimeOS)
    fmt.Println("Architecture: ", runtimeARCH)
    vmStat, err := mem.VirtualMemory()
    errHandler(err)
    fmt.Println("Total memory: ", strconv.FormatUint(vmStat.Total/(1024*1024), 10)+" MB")
    fmt.Println("Free memory: ", strconv.FormatUint(vmStat.Free/(1024*1024), 10)+" MB")

    // Cached and swap memory are ignored. Should be considered to get the understanding of the used %
    fmt.Println("Percentage used memory: ", strconv.FormatFloat(vmStat.UsedPercent, 'f', 2, 64)+"%")
}
Run Code Online (Sandbox Code Playgroud)