Wie profiliere ich Benchmarks mit dem pprof-Tool?
-
21-12-2019 - |
Frage
Ich möchte Profil meine Benchmarks generiert von go test -c
, aber die go tool pprof
benötigt eine Profildatei, die normalerweise innerhalb der Hauptfunktion generiert wird, z Das:
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
Wie kann ich eine Profildatei innerhalb meiner Benchmarks erstellen?
Lösung
Wie beschrieben in http://golang.org/cmd/go/#hdr-Description_of_testing_flags Sie können die Profildatei mithilfe des Flags angeben -cpuprofile
.
Zum Beispiel
go test -cpuprofile cpu.out
Andere Tipps
Benutzen Sie die -cpuprofile
Flagge zu go test
wie dokumentiert unter http://golang.org/cmd/go/#hdr-Description_of_testing_flags
In diesem Beitrag wird anhand eines Beispiels erläutert, wie Benchmarks profiliert werden: Benchmark-Profiling mit pprof.
Der folgende Benchmark simuliert etwas CPU-Arbeit.
package main
import (
"math/rand"
"testing"
)
func BenchmarkRand(b *testing.B) {
for n := 0; n < b.N; n++ {
rand.Int63()
}
}
Führen Sie Folgendes aus, um ein CPU-Profil für den Benchmark-Test zu generieren:
go test -bench=BenchmarkRand -benchmem -cpuprofile profile.out
Der -memprofile
Und -blockprofile
Flags können zum Generieren von Speicherzuweisungs- und Blockierungsanrufprofilen verwendet werden.
Um das Profil zu analysieren, verwenden Sie das Go-Tool:
go tool pprof profile.out
(pprof) top
Showing nodes accounting for 1.16s, 100% of 1.16s total
Showing top 10 nodes out of 22
flat flat% sum% cum cum%
0.41s 35.34% 35.34% 0.41s 35.34% sync.(*Mutex).Unlock
0.37s 31.90% 67.24% 0.37s 31.90% sync.(*Mutex).Lock
0.12s 10.34% 77.59% 1.03s 88.79% math/rand.(*lockedSource).Int63
0.08s 6.90% 84.48% 0.08s 6.90% math/rand.(*rngSource).Uint64 (inline)
0.06s 5.17% 89.66% 1.11s 95.69% math/rand.Int63
0.05s 4.31% 93.97% 0.13s 11.21% math/rand.(*rngSource).Int63
0.04s 3.45% 97.41% 1.15s 99.14% benchtest.BenchmarkRand
0.02s 1.72% 99.14% 1.05s 90.52% math/rand.(*Rand).Int63
0.01s 0.86% 100% 0.01s 0.86% runtime.futex
0 0% 100% 0.01s 0.86% runtime.allocm
Der Flaschenhals ist in diesem Fall der Mutex, der durch die Synchronisierung der Standardquelle in math/rand verursacht wird.
Auch andere Profildarstellungen und Ausgabeformate sind möglich, z.B. tree
.Typ help
für weitere Optionen.
Beachten Sie, dass auch jeder Initialisierungscode vor der Benchmark-Schleife profiliert wird.