|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "net/http" |
| 8 | + _ "net/http/pprof" |
| 9 | + "runtime/pprof" |
| 10 | + "sync" |
| 11 | + "time" |
| 12 | +) |
| 13 | + |
| 14 | +func oneWorkItem(_ context.Context, leakySliceEntry []string) { |
| 15 | + fmt.Printf("Start: %v\n", time.Now()) |
| 16 | + |
| 17 | + // Memory |
| 18 | + for i := 0; i < 500000; i++ { |
| 19 | + leakySliceEntry = append(leakySliceEntry, "aaaa") |
| 20 | + } |
| 21 | + |
| 22 | + // Blocking |
| 23 | + time.Sleep(2 * time.Second) |
| 24 | + fmt.Printf("End: %v\n", time.Now()) |
| 25 | +} |
| 26 | + |
| 27 | +// Some function that does work |
| 28 | +func hardWork(ctx context.Context, wg *sync.WaitGroup, leakySlice [][]string) { |
| 29 | + defer wg.Done() |
| 30 | + |
| 31 | + var counter int |
| 32 | + for { |
| 33 | + pprof.Do(ctx, |
| 34 | + pprof.Labels("instance", fmt.Sprintf("instance%d", counter)), |
| 35 | + func(ctx context.Context) { |
| 36 | + leakySliceEntry := make([]string, 0) |
| 37 | + leakySlice = append(leakySlice, leakySliceEntry) |
| 38 | + oneWorkItem(ctx, leakySliceEntry) |
| 39 | + }) |
| 40 | + counter++ |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +func main() { |
| 45 | + var wg sync.WaitGroup |
| 46 | + wg.Add(1) |
| 47 | + go func() { |
| 48 | + fmt.Println("Listening on localhost:6060 for pprof, use \"go tool pprof -seconds 5 http://localhost:6060/debug/pprof/heap\" to check heap profile.") |
| 49 | + log.Printf("Listener started: %s\n", http.ListenAndServe("localhost:6060", nil)) |
| 50 | + fmt.Println("Done listening") |
| 51 | + wg.Done() |
| 52 | + }() |
| 53 | + wg.Add(1) |
| 54 | + ctx := pprof.WithLabels(context.Background(), pprof.Labels("name", "hardWork")) |
| 55 | + var leakySlice [][]string |
| 56 | + go hardWork(ctx, &wg, leakySlice) |
| 57 | + wg.Wait() |
| 58 | +} |
0 commit comments