Skip to content

Instantly share code, notes, and snippets.

@juwencheng
Created January 12, 2017 03:02
Show Gist options
  • Save juwencheng/028c2c9d20d5126d6f9b67f877eff823 to your computer and use it in GitHub Desktop.
Save juwencheng/028c2c9d20d5126d6f9b67f877eff823 to your computer and use it in GitHub Desktop.
通过pid查看消耗内存
// ref: http://stackoverflow.com/questions/31879817/golang-os-exec-realtime-memory-usage?noredirect=1&lq=1
func calculateMemory(pid int) (uint64, error) {
f, err := os.Open(fmt.Sprintf("/proc/%d/smaps", pid))
if err != nil {
return 0, err
}
defer f.Close()
res := uint64(0)
pfx := []byte("Pss:")
r := bufio.NewScanner(f)
for r.Scan() {
line := r.Bytes()
if bytes.HasPrefix(line, pfx) {
var size uint64
_, err := fmt.Sscanf(string(line[4:]), "%d", &size)
if err != nil {
return 0, err
}
res += size
}
}
if err := r.Err(); err != nil {
return 0, err
}
return res, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment