Usman Ismail
Usman Ismail

Reputation: 18659

How to get total memory/RAM in GO?

How can I get the total amount of memory/RAM attached to a system in Go? I want to use native code only if possible. I have found a library that wraps linux sysinfo command. Is there a more elegant way?

Upvotes: 23

Views: 28056

Answers (4)

Volodya Lombrozo
Volodya Lombrozo

Reputation: 3454

You can read /proc/meminfo file directly in your Go program, as @Intermerne suggests. For example, you have the next structure:

type Memory struct {
    MemTotal     int
    MemFree      int
    MemAvailable int
}

You can just fill structure from the /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
}

Here is a code of parsing separate line (but I think it could be done more efficiently):

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
}

More about "/proc/meminfo" you can read from the documentation

Upvotes: 7

Tobias Pfandzelter
Tobias Pfandzelter

Reputation: 357

In my research on this I came across the memory package that implements this for a number of different platforms. If you're looking for a quick and easy solution without CGO, this might be your best option.

From the README:

package main

import (
    "fmt"
    "github.com/pbnjay/memory"
)

func main() {
    fmt.Printf("Total system memory: %d\n", memory.TotalMemory())
}

On go Playground:

Total system memory: 104857600

Upvotes: 3

Pedro Lobito
Pedro Lobito

Reputation: 98921

Besides runtime.MemStats you can use gosigar to monitor system memory.

Upvotes: 15

user5269986
user5269986

Reputation: 181

cgo & linux solution

package main

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

func main() {
    println(C.sysconf(C._SC_PHYS_PAGES)*C.sysconf(C._SC_PAGE_SIZE), " bytes")
}

Upvotes: 18

Related Questions