Dong.Ge

左手代码 右手江湖

golang 获取内存占用

东哥's Avatar 2019-07-03

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
package main

import (
"fmt"
"runtime"
"strings"
"syscall"
)

type MemStatus struct {
All uint64 `json:"all"`
Used uint64 `json:"used"`
Free uint64 `json:"free"`
Self uint64 `json:"self"`
}

func MemStat() MemStatus {
//自身占用
memStat := new(runtime.MemStats)
runtime.ReadMemStats(memStat)
mem := MemStatus{}
mem.Self = memStat.Alloc

//系统占用,仅linux/mac下有效
//system memory usage
sysInfo := new(syscall.Sysinfo_t)
err := syscall.Sysinfo(sysInfo)
// fmt.Printf("%T",sysInfo.Totalram)
if err == nil {
mem.All = sysInfo.Totalram * uint64(syscall.Getpagesize())
mem.Free = sysInfo.Freeram * uint64(syscall.Getpagesize())
mem.Used = mem.All - mem.Free
}
return mem
}

func main() {
var m runtime.MemStats
wcd := strings.Repeat("ok", 10000000)
bef := MemStat()
fmt.Println(bef.Used)
runtime.ReadMemStats(&m)
fmt.Printf("%d,%d,%d,%d\n", m.HeapSys, m.HeapAlloc,m.HeapIdle, m.HeapReleased)
wcd = ""
//runtime.GC()
//debug.FreeOSMemory()
bef = MemStat()
fmt.Println(bef.Used)
runtime.ReadMemStats(&m)
fmt.Printf("%d,%d,%d,%d\n", m.HeapSys, m.HeapAlloc,m.HeapIdle, m.HeapReleased)
_=wcd
/*
HeapSys:程序向应用程序申请的内存

HeapAlloc:堆上目前分配的内存

HeapIdle:堆上目前没有使用的内存

HeapReleased:回收到操作系统的内存

*/
}
本文最后更新于 天前,文中所描述的信息可能已发生改变