Senior
Hogyan csatlakoztassuk a profiler-t Go-ban? Hogyan készítsünk profilokat?
sobes.tech MI
Válasz az MI-től
Go-ban a profilozáshoz a net/http/pprof és a runtime/pprof csomagokat használják.
A profilozó HTTP-szerverhez való csatlakoztatásához elegendő importálni:
import _ "net/http/pprof"
és elindítani a HTTP-szervert, például:
import (
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
http.ListenAndServe(":6060", nil)
}()
// alkalmazás többi kódja
}
A futás után profilokat lehet készíteni az endpointokhoz való hozzáféréssel:
http://localhost:6060/debug/pprof/profile— CPU profil (alapértelmezett 30 másodperc)http://localhost:6060/debug/pprof/heap— memória profilhttp://localhost:6060/debug/pprof/goroutine— goroutine állapot
A CPU profil programozottan fájlba mentéséhez:
import (
"os"
"runtime/pprof"
)
func main() {
f, _ := os.Create("cpu.prof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
// profilálandó kód
}
A profilok elemzéséhez a go tool pprof parancsot használják.