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.
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
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?