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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.