1package stress23import (4 "runtime"5 "runtime/metrics"6 "time"7)89// SamplePeak samples the heap's live objects every 100 us until the10// function it returns is called, which returns the most seen.11func SamplePeak() func() uint64 {12 sample := []metrics.Sample{{Name: "/memory/classes/heap/objects:bytes"}}13 read := func() uint64 {14 metrics.Read(sample)15 return sample[0].Value.Uint64()16 }17 done := make(chan struct{})18 peak := make(chan uint64)19 go func() {20 hi := read()21 t := time.NewTicker(100 * time.Microsecond)22 defer t.Stop()23 for {24 select {25 case <-done:26 peak <- max(hi, read())27 return28 case <-t.C:29 hi = max(hi, read())30 }31 }32 }()33 return func() uint64 {34 close(done)35 return <-peak36 }37}3839// LiveHeap is the heap in use after a collection.40func LiveHeap() uint64 {41 runtime.GC()42 var ms runtime.MemStats43 runtime.ReadMemStats(&ms)44 return ms.HeapAlloc45}