Skip to content

Commit

Permalink
chore: prioritize reading smaps_rollup if possible
Browse files Browse the repository at this point in the history
  • Loading branch information
flowerinthenight committed May 30, 2024
1 parent bdb6df5 commit 8659e25
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion memx.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,38 @@ import (
"strings"
)

// GetMemoryUsage returns the calling process' internal + shared memory usage in kB.
// Faster version. Prioritize in call.
func getMemRollup() (uint64, error) {
f, err := os.Open(fmt.Sprintf("/proc/%d/smaps_rollup", os.Getpid()))
if err != nil {
return 0, err
}

defer f.Close()
r := bufio.NewScanner(f)
for r.Scan() {
line := r.Bytes()
if bytes.HasPrefix(line, []byte("Pss:")) {
var mem uint64
_, err := fmt.Sscanf(string(line[4:]), "%d", &mem)
if err != nil {
return 0, err
}

return mem, nil
}
}

return 0, fmt.Errorf("not found")
}

// GetMemoryUsage returns the calling process' private + shared memory usage in kB.
func GetMemoryUsage() (uint64, error) {
memr, err := getMemRollup()
if err == nil {
return memr, nil
}

f, err := os.Open(fmt.Sprintf("/proc/%d/smaps", os.Getpid()))
if err != nil {
return 0, err
Expand Down

0 comments on commit 8659e25

Please sign in to comment.