Senior
Hoe sluit je een profiler aan in Go? Hoe neem je profielen op?
sobes.tech AI
Antwoord van AI
In Go worden de pakketten net/http/pprof en runtime/pprof gebruikt voor profiling.
Om de profiler aan de HTTP-server te koppelen, hoeft u alleen te importeren:
import _ "net/http/pprof"
en start de HTTP-server, bijvoorbeeld:
import (
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
http.ListenAndServe(":6060", nil)
}()
// rest van de applicatiecode
}
Na het starten kunt u profielen maken door naar de endpoints te gaan:
http://localhost:6060/debug/pprof/profile— CPU-profiel (standaard 30 seconden)http://localhost:6060/debug/pprof/heap— geheugengebruik profielhttp://localhost:6060/debug/pprof/goroutine— toestand van goroutines
Om het CPU-profiel programmatisch naar een bestand te schrijven:
import (
"os"
"runtime/pprof"
)
func main() {
f, _ := os.Create("cpu.prof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
// code om te profileren
}
Voor profielanalyse wordt de opdracht go tool pprof gebruikt.