testing.B.Loop() standardization and StackAsync.Debug improvement (#156)

* testing.B.Loop() standardization and StackAsync.Debug heap debugging improvement

* apply @MDr164 fixes

* @MDr164 great suggestions to prevent panic and print correct mallocs
This commit is contained in:
Pat Whittingslow
2026-07-17 11:59:27 -03:00
committed by GitHub
parent 766e03e90e
commit 157a8537a2
10 changed files with 64 additions and 45 deletions
+29 -14
View File
@@ -2,16 +2,16 @@ package internal
import (
"log/slog"
"os"
"runtime"
"strconv"
"sync"
"unsafe"
)
const (
LevelTrace slog.Level = slog.LevelDebug - 2
usePrintLogAllocs = true
usePrintLogAllocs = HeapAllocDebugging
)
var (
@@ -19,9 +19,13 @@ var (
lastAllocs uint64
lastMallocs uint64
allocmu sync.Mutex
allocbuf [256]byte
allocbuf [128]byte
)
func LogAttrsAndAllocs(allocmsg string, l *slog.Logger, level slog.Level, msg string, attrs ...slog.Attr) {
logAttrsAndAllocs(allocmsg, l, level, msg, attrs...)
}
func LogAllocs(msg string) {
allocmu.Lock()
runtime.ReadMemStats(&memstats)
@@ -29,23 +33,34 @@ func LogAllocs(msg string) {
allocmu.Unlock()
return
}
inc := int64(memstats.TotalAlloc) - int64(lastAllocs)
numAlloc := int64(memstats.Mallocs) - int64(lastMallocs)
free := memstats.HeapSys - memstats.HeapInuse
if usePrintLogAllocs {
// Branch used when debugheaplog enabled
print("[ALLOC] ", msg)
print(" inc=", int64(memstats.TotalAlloc)-int64(lastAllocs))
print(" n=", int64(memstats.Mallocs)-int64(lastMallocs))
print(" inc=", inc)
print(" n=", numAlloc)
print(" heap=", memstats.HeapAlloc)
print(" free=", memstats.HeapSys-memstats.HeapInuse)
print(" free=", free)
print(" tot=", memstats.TotalAlloc)
println()
} else {
n := copy(allocbuf[:], "[ALLOC] ")
n += copy(allocbuf[n:], msg)
n += copyValueInt(allocbuf[n:], "inc", int64(memstats.TotalAlloc)-int64(lastAllocs))
n += copyValueInt(allocbuf[n:], "n", int64(memstats.Mallocs)-int64(lastMallocs))
n += copyValueUint(allocbuf[n:], "heap", memstats.HeapAlloc)
n += copyValueUint(allocbuf[n:], "free", memstats.HeapSys-memstats.HeapInuse)
n += copyValueUint(allocbuf[n:], "tot", memstats.TotalAlloc)
println(unsafe.String(&allocbuf[0], n))
buf := allocbuf[:len(allocbuf)-1] // keep one character for newline.
n := copy(buf[:], "[ALLOC] ")
n += copy(buf[n:], msg)
n += copyValueInt(buf[n:], "inc", inc)
n += copyValueInt(buf[n:], "n", numAlloc)
n += copyValueUint(buf[n:], "heap", memstats.HeapAlloc)
n += copyValueUint(buf[n:], "free", free)
lastN := copyValueUint(buf[n:], "tot", memstats.TotalAlloc)
n += lastN
allocbuf[n] = '\n' // n will never be larger than len(allocbuf)-1
os.Stdout.Write(allocbuf[:n+1])
if lastN == 0 {
n2 := copy(allocbuf[:], "[WARN] ALLOC BUF OVERRUN\n")
os.Stdout.Write(allocbuf[:n2])
}
}
lastAllocs = memstats.TotalAlloc
lastMallocs = memstats.Mallocs