Senior
How to connect a profiler in Go? How to take profiles?
sobes.tech AI
Answer from AI
In Go, profiling is done using the net/http/pprof package and the runtime/pprof package.
To attach the profiler to an HTTP server, simply import:
import _ "net/http/pprof"
and start the HTTP server, for example:
import (
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
http.ListenAndServe(":6060", nil)
}()
// rest of the application code
}
After starting, you can take profiles by accessing the endpoints:
http://localhost:6060/debug/pprof/profile— CPU profile (default 30 seconds)http://localhost:6060/debug/pprof/heap— memory profilehttp://localhost:6060/debug/pprof/goroutine— goroutine state
To programmatically record a CPU profile to a file:
import (
"os"
"runtime/pprof"
)
func main() {
f, _ := os.Create("cpu.prof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
// code to profile
}
Profiles are analyzed using the go tool pprof command.