在Go 1.3.1中获取可变的内存使用情况

  1. Why this code can not found the memory usage (m2-m1) and (m4-m3)?
  2. Why (m3-m2) and (m5-m4) require to allocate extra memory?

Full code here

type T struct {
    B uint8
    S string
    I int
}

func memUsage(mOld, mNew *runtime.MemStats) {
    fmt.Println("Alloc:", mNew.Alloc-mOld.Alloc,
        "HeapAlloc:", mNew.HeapAlloc-mOld.HeapAlloc,
        "TotalAlloc:", mNew.TotalAlloc-mOld.TotalAlloc)
}
func main() {
    var m1, m2, m3, m4, m5, m6 runtime.MemStats
    runtime.ReadMemStats(&m1)
    t := T{}
    runtime.ReadMemStats(&m2)
    fmt.Println(t)
    memUsage(&m1, &m2)

    runtime.ReadMemStats(&m3)
    t2 := "abc"
    runtime.ReadMemStats(&m4)
    fmt.Println(t2)
    memUsage(&m3, &m4)

    runtime.ReadMemStats(&m5)
    t3 := map[int]string{1: "x"}
    runtime.ReadMemStats(&m6)
    fmt.Println(t3)
    memUsage(&m5, &m6)

    memUsage(&m2, &m3)
    memUsage(&m4, &m5)
}

Output

{0  0}
Alloc: 0 HeapAlloc: 0 TotalAlloc: 0
abc
Alloc: 0 HeapAlloc: 0 TotalAlloc: 0
map[1:x]
Alloc: 256 HeapAlloc: 256 TotalAlloc: 256
Alloc: 432 HeapAlloc: 432 TotalAlloc: 432
Alloc: 64 HeapAlloc: 64 TotalAlloc: 64
查看全部
dongya2030
dongya2030
2014/09/08 01:12
  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复