How to get total memory/RAM in GO?
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")
}
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
Besides runtime.MemStats you can use gosigar to monitor system memory.
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