Skip to content

Commit 0df3723

Browse files
committed
Add AvailableMemory for Linux
1 parent 7b4eea6 commit 0df3723

File tree

5 files changed

+41
-0
lines changed

5 files changed

+41
-0
lines changed

doc.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,13 @@ func TotalMemory() uint64 {
2222
func FreeMemory() uint64 {
2323
return sysFreeMemory()
2424
}
25+
26+
// AvailableMemory returns the total free+freeable system memory in bytes.
27+
//
28+
// The total available memory is the free memory + freeable memory
29+
// such as buffer and cache.
30+
//
31+
// If free memory size could not be determined, then 0 is returned.
32+
func AvailableMemory() uint64 {
33+
return sysAvailableMemory()
34+
}

memory_bsd.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//go:build freebsd || openbsd || dragonfly || netbsd
12
// +build freebsd openbsd dragonfly netbsd
23

34
package memory
@@ -17,3 +18,7 @@ func sysFreeMemory() uint64 {
1718
}
1819
return s
1920
}
21+
22+
func sysAvailableMemory() uint64 {
23+
return sysFreeMemory()
24+
}

memory_darwin.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//go:build darwin
12
// +build darwin
23

34
package memory
@@ -47,3 +48,7 @@ func sysFreeMemory() uint64 {
4748
}
4849
return freePages * pageSize
4950
}
51+
52+
func sysAvailableMemory() uint64 {
53+
return sysFreeMemory()
54+
}

memory_linux.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//go:build linux
12
// +build linux
23

34
package memory
@@ -27,3 +28,18 @@ func sysFreeMemory() uint64 {
2728
// So we always convert to uint64 to match signature.
2829
return uint64(in.Freeram) * uint64(in.Unit)
2930
}
31+
32+
func sysAvailableMemory() uint64 {
33+
in := &syscall.Sysinfo_t{}
34+
err := syscall.Sysinfo(in)
35+
if err != nil {
36+
return 0
37+
}
38+
// If this is a 32-bit system, then these fields are
39+
// uint32 instead of uint64.
40+
// So we always convert to uint64 to match signature.
41+
// Buffer/cache ram is included on linux since the kernel
42+
// will free this memory for applications if needed, and tends
43+
// to use almost all free memory for itself when it can.
44+
return (uint64(in.Freeram) + uint64(in.Bufferram)) * uint64(in.Unit)
45+
}

memory_windows.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//go:build windows
12
// +build windows
23

34
package memory
@@ -58,3 +59,7 @@ func sysFreeMemory() uint64 {
5859
}
5960
return msx.ullAvailPhys
6061
}
62+
63+
func sysAvailableMemory() uint64 {
64+
return sysFreeMemory()
65+
}

0 commit comments

Comments
 (0)