runtime/debug is a package for debugging and managing the Go runtime.
1import "runtime/debug"23func main() {4 // Build information5 info, ok := debug.ReadBuildInfo()6 if ok {7 fmt.Println("Go version:", info.GoVersion)8 fmt.Println("Module:", info.Main.Path)9 for _, dep := range info.Deps {10 fmt.Printf(" %s@%s\n", dep.Path, dep.Version)11 }12 }1314 // Stack of all goroutines15 buf := make([]byte, 1<<20)16 n := runtime.Stack(buf, true) // true = all goroutines17 fmt.Println(string(buf[:n]))1819 // GC configuration20 debug.SetGCPercent(200) // GC when memory doubles21 debug.SetMemoryLimit(1 << 30) // 1GB limit (Go 1.19+)2223 // Limiting goroutine count24 debug.SetMaxThreads(500)2526 // Limiting stack27 debug.SetMaxStack(256 << 20) // 256MB2829 // Disable GC30 debug.SetGCPercent(-1)31 debug.SetMemoryLimit(0)32 runtime.GC() // Collect garbage before disabling33}3435// Stack trace for a specific goroutine36func getStackTrace() string {37 buf := make([]byte, 1<<16)38 n := runtime.Stack(buf, false) // false = current only39 return string(buf[:n])40}4142// Freeze GC (for debugging)43runtime.GC()44debug.FreeOSMemory() // Free OS memory
Useful functions: