How to collect information about garbage collection?


Under runtime/debug package function GCStats collects information about recent garbage collections. And PrintStack prints to standard error the stack trace returned by runtime.Stack.

Example

package main

import (
	"flag"
	"fmt"
	"runtime/debug"
)

var (
	garPercent = flag.Int("garC", 50, "Collect information about recent garbage collections")
)

func main() {
	debug.SetGCPercent(*garPercent)
	debug.PrintStack()	
	
	var garC debug.GCStats
	debug.ReadGCStats(&garC)
	fmt.Printf("\nLastGC:\t%s", garC.LastGC) // time of last collection
	fmt.Printf("\nNumGC:\t%d", garC.NumGC) // number of garbage collections
	fmt.Printf("\nPauseTotal:\t%s", garC.PauseTotal) // total pause for all collections
	fmt.Printf("\nPause:\t%s", garC.Pause) // pause history, most recent first	
}

Output

goroutine 1 [running]:
runtime/debug.Stack(0x4122b6, 0x2, 0x0)
        C:/Go/src/runtime/debug/stack.go:24 +0x64
runtime/debug.PrintStack()
        C:/Go/src/runtime/debug/stack.go:16 +0x1a
main.main()
        C:/golang/codes/example.go:15 +0x2e

LastGC: 2017-10-29 13:54:12.9605418 +0530 IST
NumGC:  1
PauseTotal:     0s
Pause:  [0s]
Most Helpful This Week