runtime

Guided tour · Runtime & Debug · pkg.go.dev →

Hooks into the Go runtime: GOMAXPROCS, goroutine count, GC triggering, caller info, finalizers.

CPU and goroutines

GOMAXPROCS

old := runtime.GOMAXPROCS(4)
runtime.GOMAXPROCS(runtime.NumCPU())

NumGoroutine

fmt.Println("goroutines:", runtime.NumGoroutine())

Gosched / Goexit

runtime.Gosched() // yield to scheduler
runtime.Goexit()   // terminate current goroutine (deferred funcs still run)

GC

Force GC

runtime.GC()          // blocking full GC
debug.SetGCPercent(200) // tune GC trigger (debug package)

MemStats

var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Println(m.HeapAlloc, m.NumGC)

Caller info

Caller / Callers

pc, file, line, ok := runtime.Caller(1)
if ok {
    fn := runtime.FuncForPC(pc)
    fmt.Printf("%s at %s:%d\n", fn.Name(), file, line)
}

Finalizers and cleanups

SetFinalizer (legacy)

runtime.SetFinalizer(obj, func(o *T) { o.Close() })

AddCleanup (Go 1.24+)

runtime.AddCleanup(obj, func(h *Handle) { h.Free() }, handle)

Runtime info

GOOS / GOARCH / Version

fmt.Println(runtime.GOOS, runtime.GOARCH, runtime.Version())