0

我正在学习 Go Profilig 的工作原理。所以我做了下面的例子

func Func() {

    var b [][]byte

    for i := 0; i < 8; i++ {
        b = append(b, make([]byte, 8))
    }

}

func BenchmarkFunc(b *testing.B) {

    for i:=0; i<b.N; i++ {
        Func()
    }
}

然后我跑

go test -run none -bench Func -benchmem -memprofile mem.out

go tool pprof -alloc_space mem.out 
(pprof) list Func

我得到的是

Total: 1.61GB
ROUTINE ======================== test-mem/somepkg.BenchmarkFunc in .../work/go/src/test-mem/somepkg/somepkg_test.go
         0     1.61GB (flat, cum)   100% of Total
         .          .     14://
         .          .     15:
         .          .     16:func BenchmarkFunc(b *testing.B) {
         .          .     17:
         .          .     18:   for i:=0; i<b.N; i++ {
         .     1.61GB     19:           Func()
         .          .     20:   }
         .          .     21:}
ROUTINE ======================== test-mem/somepkg.Func in .../go/src/test-mem/somepkg/somepkg.go
    1.61GB     1.61GB (flat, cum)   100% of Total
         .          .     42:func Func() {
         .          .     43:
         .          .     44:   var b [][]byte
         .          .     45:
         .          .     46:   for i := 0; i < 8; i++ {
    1.61GB     1.61GB     47:           b = append(b, make([]byte, 8))
         .          .     48:   }
         .          .     49:
         .          .     50:}

为什么我得到1.61GB分配?是不是太多了?如何检查一个函数运行内存分配是什么?

4

0 回答 0