-
Notifications
You must be signed in to change notification settings - Fork 0
/
memx.go
74 lines (62 loc) · 1.24 KB
/
memx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package memx
import (
"bufio"
"bytes"
"fmt"
"os"
"strings"
)
// 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
}
defer f.Close()
var mem uint64
r := bufio.NewScanner(f)
for r.Scan() {
line := r.Bytes()
if !bytes.HasPrefix(line, []byte("Pss:")) {
continue
}
var size uint64
var unit string
_, err := fmt.Sscanf(string(line[4:]), "%d %s", &size, &unit)
if err != nil {
return 0, err
}
if strings.ToLower(unit) == "kb" {
mem += size
}
}
if r.Err() != nil {
return 0, err
}
return mem, nil
}