From ea268d3158637e7d57f76d182cda72bc0adef22c Mon Sep 17 00:00:00 2001 From: Dustin Decker Date: Thu, 10 Mar 2022 21:15:49 -0800 Subject: [PATCH] Add AvailableMemory for Linux --- doc.go | 10 ++++++++++ memory_bsd.go | 5 +++++ memory_darwin.go | 5 +++++ memory_linux.go | 16 ++++++++++++++++ memory_windows.go | 5 +++++ 5 files changed, 41 insertions(+) diff --git a/doc.go b/doc.go index 4e4f984..862d8a1 100644 --- a/doc.go +++ b/doc.go @@ -22,3 +22,13 @@ func TotalMemory() uint64 { func FreeMemory() uint64 { return sysFreeMemory() } + +// AvailableMemory returns the total free+freeable system memory in bytes. +// +// The total available memory is the free memory + freeable memory +// such as buffer and cache. +// +// If available memory size could not be determined, then 0 is returned. +func AvailableMemory() uint64 { + return sysAvailableMemory() +} diff --git a/memory_bsd.go b/memory_bsd.go index 49d808a..ed18ff1 100644 --- a/memory_bsd.go +++ b/memory_bsd.go @@ -1,3 +1,4 @@ +//go:build freebsd || openbsd || dragonfly || netbsd // +build freebsd openbsd dragonfly netbsd package memory @@ -17,3 +18,7 @@ func sysFreeMemory() uint64 { } return s } + +func sysAvailableMemory() uint64 { + return sysFreeMemory() +} diff --git a/memory_darwin.go b/memory_darwin.go index a3f4576..5019cfd 100644 --- a/memory_darwin.go +++ b/memory_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package memory @@ -47,3 +48,7 @@ func sysFreeMemory() uint64 { } return freePages * pageSize } + +func sysAvailableMemory() uint64 { + return sysFreeMemory() +} diff --git a/memory_linux.go b/memory_linux.go index 3d07711..ad75f20 100644 --- a/memory_linux.go +++ b/memory_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package memory @@ -27,3 +28,18 @@ func sysFreeMemory() uint64 { // So we always convert to uint64 to match signature. return uint64(in.Freeram) * uint64(in.Unit) } + +func sysAvailableMemory() uint64 { + in := &syscall.Sysinfo_t{} + err := syscall.Sysinfo(in) + if err != nil { + return 0 + } + // If this is a 32-bit system, then these fields are + // uint32 instead of uint64. + // So we always convert to uint64 to match signature. + // Buffer/cache ram is included on linux since the kernel + // will free this memory for applications if needed, and tends + // to use almost all free memory for itself when it can. + return (uint64(in.Freeram) + uint64(in.Bufferram)) * uint64(in.Unit) +} diff --git a/memory_windows.go b/memory_windows.go index c8500cc..fa8014e 100644 --- a/memory_windows.go +++ b/memory_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package memory @@ -58,3 +59,7 @@ func sysFreeMemory() uint64 { } return msx.ullAvailPhys } + +func sysAvailableMemory() uint64 { + return sysFreeMemory() +}