Runtime MemStats Inspect Heap And GC

Read runtime.ReadMemStats once to observe heap allocation and GC counters; values change per run, so treat them as diagnostics rather than promises.

GoData Integrity

Code

gosnippet
25 lines
package main

import (
	"fmt"
	"runtime"
)

func main() {
	// 分配一些内存,制造可观察的堆活动
	_ = make([]byte, 1<<20)

	var stats runtime.MemStats
	runtime.ReadMemStats(&stats)

	// 这些计数器是运行时快照:每次运行数值不同,只作诊断
	fmt.Println("heap alloc bytes:", stats.HeapAlloc)
	fmt.Println("heap objects:", stats.HeapObjects)
	fmt.Println("total gc cycles:", stats.NumGC)

	// 手动触发一次 GC 后 NumGC 至少 +1
	runtime.GC()
	runtime.ReadMemStats(&stats)
	fmt.Println("gc cycles after runtime.GC():", stats.NumGC)
	fmt.Println("last gc pause ns:", stats.PauseNs[(stats.NumGC+255)%256])
}

What runs when

Count the function main as the entire surface area of Runtime MemStats Inspect Heap And GC.

Putting it to use

Each run prints the 5 labeled blocks heap alloc bytes:, heap objects:, total gc cycles:, gc cycles after runtime.GC():, last gc pause ns: in source order.

Core lines

_ = make([]byte, 1<<20)

Interactive Tools for This Topic

FAQ

What does Runtime MemStats Inspect Heap And GC print when run?
Execute the whole file; each printed line is prefixed with a label like `heap alloc bytes:`, `heap objects:`, `total gc cycles:`.