How do I use pprof for memory profiling?

Using pprof for memory profiling in Go is an essential technique for understanding memory usage and identifying potential memory leaks in your applications. By following these steps, you can generate heap profiles to analyze your program's memory allocations.

Example of Memory Profiling with pprof

package main import ( "net/http" "net/http/pprof" "log" "runtime" "runtime/pprof" "os" ) func main() { // Start pprof for HTTP profiling go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }() // Create memory profile file f, err := os.Create("memprofile.prof") if err != nil { log.Fatal(err) } defer f.Close() // Run some code that consumes memory performMemoryIntensiveOperation() // Take a memory profile runtime.GC() // run garbage collection if err := pprof.WriteHeapProfile(f); err != nil { log.Fatal(err) } } func performMemoryIntensiveOperation() { // Simulate memory allocation data := make([]byte, 10e6) // Allocate 10MB _ = data }

pprof memory profiling Go programming Go memory management profiling Go applications