CodeBlanks Logo Icon CodeBlanks

Memory profiling

Learn memory profile and the alloc distinction.

Memory profiling

The heap profile has two views: inuse (memory held right now; for hunting leaks) and alloc (total allocated since start; for reducing GC pressure).

go tool pprof -sample_index=inuse_space http://localhost:6060/debug/pprof/heap
go tool pprof -sample_index=alloc_space http://localhost:6060/debug/pprof/heap

To write to a file use pprof.WriteHeapProfile(f).

runtime.MemStats

For a quick measurement runtime.ReadMemStats is enough instead of a profile:

var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Println("heap:", m.HeapAlloc/1024, "KB", "GC:", m.NumGC)

HeapAlloc gives the heap held, TotalAlloc the total allocated and NumGC the number of collections. The call needs a brief stop-the-world; don't call it often.

Practice Measure allocation

Read TotalAlloc with runtime.ReadMemStats, then allocate 1 MB with make([]byte, 1<<20) and measure again. Print whether the difference is at least 1 MB (diff >= 1<<20).

Starter code

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "runtime"
)

var sink []byte

func main() {
    var a, b runtime.MemStats
    runtime.ReadMemStats(&a)
    sink = make([]byte, 1<<20)
    runtime.ReadMemStats(&b)
    fark := b.TotalAlloc - a.TotalAlloc
    fmt.Println(fark >= 1<<20)
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If memory keeps growing, which view do you check first?

  • inuse_space Correct answer
  • alloc_objects
  • The CPU profile
  • trace

Explanation: inuse shows memory still reachable; a leak is found among the growing entries there.

2 Read the stats

Question
var m runtime.MemStats
runtime.____(&m)
Answer
var m runtime.MemStats
runtime.ReadMemStats(&m)

Explanation: ReadMemStats fills the given struct with memory statistics.

3 Memory metrics

Term Meaning
inuse_space Held now
alloc_space Total allocated
HeapAlloc Live heap bytes
NumGC GC count

All lessons in Advanced