Skip to content

Pprof and trace

  1. Add pprof handlers to a router:

router.HandleFunc("/debug/pprof/", pprof.Index)  
router.PathPrefix("/debug/pprof/").Handler(http.DefaultServeMux)
or

go func() { 
    log.Println("Starting HTTP server for pprof at http://localhost:6060") 
    if err := http.ListenAndServe("localhost:6060", nil); err != nil { 
        log.Fatalf("Failed to start pprof HTTP server: %v", err) 
    } 
}()

go tool pprof -http=:8081 http://localhost:6060/debug/pprof/profile
see https://pkg.go.dev/net/http/pprof

💡 For block profile set runtime.SetBlockProfileRate(1)

  1. Use pprof to get cpu profile without handlers
import "runtime/pprof"

pprofFile, err := os.Create("cpu.pprof")  
if err != nil {  
    log.Printf("Failed to create pprof file: %v", err)  
    os.Exit(1)  
}  
defer pprofFile.Close()  
err = pprof.StartCPUProfile(pprofFile)  
if err != nil {  
    log.Printf("Failed to start pprof: %v", err)  
    os.Exit(1)  
}  
defer pprof.StopCPUProfile()

Trace

import "runtime/trace"

traceFile, err := os.Create("trace.out")  
if err != nil {  
    log.Printf("Failed to create trace file file: %v", err)  
    os.Exit(1)  
}  
defer traceFile.Close()  
err = trace.Start(traceFile)  
if err != nil {  
    log.Printf("Failed to start trace: %v", err)  
    os.Exit(1)  
}  
defer trace.Stop()
go tool trace trace.out
go tool trace -pprof=net trace.out