Sobes.tech
Senior

Wie verbindet man einen Profiler in Go? Wie erstellt man Profile?

sobes.tech KI

Antwort von AI

In Go werden die Pakete net/http/pprof und runtime/pprof für das Profiling verwendet.

Um den Profiler an den HTTP-Server anzuschließen, reicht es aus, zu importieren:

import _ "net/http/pprof"

und den HTTP-Server zu starten, zum Beispiel:

import (
    "net/http"
    _ "net/http/pprof"
)

func main() {
    go func() {
        http.ListenAndServe(":6060", nil)
    }()
    // restlicher Anwendungscode
}

Nach dem Start können Profile durch Zugriff auf die Endpunkte aufgenommen werden:

  • http://localhost:6060/debug/pprof/profile — CPU-Profil (Standard 30 Sekunden)
  • http://localhost:6060/debug/pprof/heap — Speicherprofil
  • http://localhost:6060/debug/pprof/goroutine — Zustand der Goroutines

Um das CPU-Profil programmatisch in eine Datei zu schreiben:

import (
    "os"
    "runtime/pprof"
)

func main() {
    f, _ := os.Create("cpu.prof")
    pprof.StartCPUProfile(f)
    defer pprof.StopCPUProfile()

    // zu profilierender Code
}

Zur Analyse der Profile wird der Befehl go tool pprof verwendet.