1

I have some Linux code in golang:

import "syscall"

var info syscall.Sysinfo_t
err := syscall.Sysinfo(&info)
totalRam := info.Totalram

I'd like to port this to Mac OS X. I see that Sysinfo is available on Linux but not on 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) {\

Mac:

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

What is the correct way to get the system RAM info on Mac?

Simon Que
  • 45
  • 4
  • Could you take a look if this fits you? https://golang.org/pkg/runtime/#ReadMemStats – Stf Kolev Apr 14 '20 at 07:15
  • Forgive my previous question, here is a package that is currently supported for cross-platform. https://pkg.go.dev/github.com/pbnjay/memory Example usage would be `fmt.Printf("Total system memory: %d\n", memory.TotalMemory())` – Stf Kolev Apr 14 '20 at 07:36
  • Could you please mark the answer as accepted if you find it useful? – shmsr Apr 16 '20 at 03:05

1 Answers1

5

This code is cross-compile supported.

Pre-requisites:

Get this package 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)+"%")
}
shmsr
  • 3,802
  • 2
  • 18
  • 29