golang程式碼中生成pprof和trace報告
摘要:
// 生成 CPU 報告
import (
"context"
"runtime/pprof"
"log"
)
func cpuProfile(ctx context.Context) {
f, er...
// 生成 CPU 報告
import ( "context" "runtime/pprof" "log" ) func cpuProfile(ctx context.Context) { f, err := os.Create("cpu.prof") if err != nil { log.Fatal(err) } log.Println("CPU Profile started") pprof.StartCPUProfile(f) go func(){ select{ case <-ctx.Done(): pprof.StopCPUProfile() f.Close() } } }
// 生成堆記憶體報告
import ( "context" "runtime/pprof" "log" ) func heapProfile(ctx context.Context) { f, err := os.Create("heap.prof") if err != nil { log.Fatal(err) } defer f.Close() pprof.WriteHeapProfile(f) go func(){ select{ case <-ctx.Done(): f.Close() } } }
// 生成trace報告
import ( "context" "runtime/trace" "log" ) func traceProfile(ctx context.Context) { f, err := os.OpenFile("trace.out") if err != nil { log.Fatal(err) } log.Println("Trace started") trace.Start(f) go func(){ select{ case <-ctx.Done(): trace.Stop() f.Close() } } }