Skip to content

Commit

Permalink
return linux avilable memory. others return free memory as defined.
Browse files Browse the repository at this point in the history
  • Loading branch information
dustin-decker committed Mar 11, 2022
1 parent 003e56d commit 1106214
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 1 deletion.
10 changes: 10 additions & 0 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 free memory size could not be determined, then 0 is returned.
func AvailableMemory() uint64 {
return sysAvailableMemory()
}
5 changes: 5 additions & 0 deletions memory_bsd.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build freebsd || openbsd || dragonfly || netbsd
// +build freebsd openbsd dragonfly netbsd

package memory
Expand All @@ -17,3 +18,7 @@ func sysFreeMemory() uint64 {
}
return s
}

func sysAvailableMemory() uint64 {
return sysFreeMemory()
}
5 changes: 5 additions & 0 deletions memory_darwin.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build darwin
// +build darwin

package memory
Expand Down Expand Up @@ -47,3 +48,7 @@ func sysFreeMemory() uint64 {
}
return freePages * pageSize
}

func sysAvailableMemory() uint64 {
return sysFreeMemory()
}
13 changes: 12 additions & 1 deletion memory_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@ func sysTotalMemory() uint64 {
}

func sysFreeMemory() 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.
return uint64(in.Freeram) * uint64(in.Unit)
}

func sysAvailableMemory() uint64 {
in := &syscall.Sysinfo_t{}
err := syscall.Sysinfo(in)
if err != nil {
Expand All @@ -29,6 +41,5 @@ func sysFreeMemory() uint64 {
// 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.
// https://pkg.go.dev/syscall#Sysinfo_t
return (uint64(in.Freeram) + uint64(in.Bufferram)) * uint64(in.Unit)
}
5 changes: 5 additions & 0 deletions memory_windows.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build windows
// +build windows

package memory
Expand Down Expand Up @@ -58,3 +59,7 @@ func sysFreeMemory() uint64 {
}
return msx.ullAvailPhys
}

func sysAvailableMemory() uint64 {
return sysFreeMemory()
}

0 comments on commit 1106214

Please sign in to comment.