Profiling global variables

Viewed 212

Is it possible to find out the memory usage of global variables in Go?

For example have a look at this code:

package main

import (
    "fmt"
    "math/rand"
    _ "net/http/pprof"
    "os"
    "runtime"
    "runtime/pprof"
    "time"
)

var globalByteArray1, globalByteArray2 []byte

func main() {
    rand.Seed(time.Now().Unix())
    globalByteArray1 = make([]byte, 10*1024*1024)
    rand.Read(globalByteArray1)
    memoryUsage()
    globalByteArray2 = make([]byte, 20*1024*1024)
    rand.Read(globalByteArray2)
    memoryUsage()
    fmt.Println(globalByteArray1[len(globalByteArray1)-1], globalByteArray2[len(globalByteArray2)-1])
    file, _ := os.Create("heap")
    pprof.WriteHeapProfile(file)
    file.Close()
    fmt.Println(globalByteArray1[len(globalByteArray1)-1], globalByteArray2[len(globalByteArray2)-1])
}

func memoryUsage() {
    var m runtime.MemStats
    runtime.ReadMemStats(&m)
    fmt.Println(m.Alloc/1024/1024, "MB")
}

This code prints the following output which is fine.

10 MB
30 MB
209 214
209 214

I thought to myself maybe pprof can show me the global variables. But it actually made me more confused.

pprof-graph pprof-flame

So I have two questions:

  1. Can I profile the global variables and see the memory usage of each one?
  2. Why is pprof showing 10MB only? What happened to globalByteArray2?
0 Answers
Related