Senior
Kā pieslēgt profiler'i Go? Kā ņemt profilus?
sobes.tech AI
Atbilde no AI
Go valodā profilēšanai tiek izmantoti pakotnes net/http/pprof un runtime/pprof.
Lai pieslēgtu profileru pie HTTP servera, pietiek tikai importēt:
import _ "net/http/pprof"
un palaist HTTP serveri, piemēram:
import (
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
http.ListenAndServe(":6060", nil)
}()
// pārējais koda daļa
}
Pēc palaišanas, profilus var ņemt, piekļūstot endpointiem:
http://localhost:6060/debug/pprof/profile— CPU profils (standarta 30 sekundes)http://localhost:6060/debug/pprof/heap— atmiņas profilshttp://localhost:6060/debug/pprof/goroutine— gorutīnu stāvoklis
Lai programmatiski saglabātu CPU profilu failā:
import (
"os"
"runtime/pprof"
)
func main() {
f, _ := os.Create("cpu.prof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
// profilējams kods
}
Profila analīzei izmanto komandu go tool pprof.