From 301b127a058c9bf3859e2a8c49e1ffc3c3398077 Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Wed, 29 Nov 2017 15:38:52 -0500 Subject: [PATCH] runtime/pprof: read memstats earlier in profile handler Reading the mem stats before our own allocations avoids cluttering memory stats with our recent garbage. Fixes #20565. Change-Id: I3b0046c8300dca83cea24013ffebc32b2ae7f742 Reviewed-on: https://go-review.googlesource.com/80739 Reviewed-by: Austin Clements Run-TryBot: Austin Clements TryBot-Result: Gobot Gobot --- src/runtime/pprof/pprof.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/runtime/pprof/pprof.go b/src/runtime/pprof/pprof.go index f76dde28d4..d3382a5589 100644 --- a/src/runtime/pprof/pprof.go +++ b/src/runtime/pprof/pprof.go @@ -509,6 +509,14 @@ func countHeap() int { // writeHeap writes the current runtime heap profile to w. func writeHeap(w io.Writer, debug int) error { + var memStats *runtime.MemStats + if debug != 0 { + // Read mem stats first, so that our other allocations + // do not appear in the statistics. + memStats = new(runtime.MemStats) + runtime.ReadMemStats(memStats) + } + // Find out how many records there are (MemProfile(nil, true)), // allocate that many records, and get the data. // There's a race—more records might be added between @@ -571,8 +579,7 @@ func writeHeap(w io.Writer, debug int) error { // Print memstats information too. // Pprof will ignore, but useful for people - s := new(runtime.MemStats) - runtime.ReadMemStats(s) + s := memStats fmt.Fprintf(w, "\n# runtime.MemStats\n") fmt.Fprintf(w, "# Alloc = %d\n", s.Alloc) fmt.Fprintf(w, "# TotalAlloc = %d\n", s.TotalAlloc) -- 2.48.1