title: Profiling global variables
body: <p>Is it possible to find out the memory usage of global variables in Go?</p>
  <p>For example have a look at this code:</p>
  <pre class="lang-go prettyprint-override"><code>package main
  
  import (
      &quot;fmt&quot;
      &quot;math/rand&quot;
      _ &quot;net/http/pprof&quot;
      &quot;os&quot;
      &quot;runtime&quot;
      &quot;runtime/pprof&quot;
      &quot;time&quot;
  )
  
  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(&quot;heap&quot;)
      pprof.WriteHeapProfile(file)
      file.Close()
      fmt.Println(globalByteArray1[len(globalByteArray1)-1], globalByteArray2[len(globalByteArray2)-1])
  }
  
  func memoryUsage() {
      var m runtime.MemStats
      runtime.ReadMemStats(&amp;m)
      fmt.Println(m.Alloc/1024/1024, &quot;MB&quot;)
  }
  </code></pre>
  <p>This code prints the following output which is fine.</p>
  <pre><code>10 MB
  30 MB
  209 214
  209 214
  </code></pre>
  <p>I thought to myself maybe <code>pprof</code> can show me the global variables. But it actually made me more confused.</p>
  <p><a href="https://i.stack.imgur.com/H2i4X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H2i4X.png" alt="pprof-graph" /></a>
  <a href="https://i.stack.imgur.com/FhKSn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FhKSn.png" alt="pprof-flame" /></a></p>
  <p>So I have two questions:</p>
  <ol>
  <li>Can I profile the global variables and see the memory usage of each one?</li>
  <li>Why is pprof showing 10MB only? What happened to <code>globalByteArray2</code>?</li>
  </ol>