Use Go tests to analyze memory usage. For instance:
mem.go:
package mem
func memUse() {
var stack [1024]byte
heap := make([]byte, 64*1024)
_, _ = stack, heap
}
mem_test.go:
package mem
import "testing"
func BenchmarkMemUse(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
memUse()
}
b.StopTimer()
}
Conclusion:
$ go test -bench=.
goos: linux
goarch: amd64
pkg: mem
BenchmarkMemUse-4 200000 8188 ns/op 65536 B/op 1 allocs/op
PASS
ok mem 1.745s
The function memUsemakes one heap allocation 65536 (64 * 1024) bytes. Stack distributions are cheap and local to the function, so we do not take them into account.
Instead of a method, ReportAllocsyou can use a flag -benchmem. For instance,
go test -bench=. -benchmem
Literature:
: :
go:
go:
Go testing, runtime.MemStats. ,
func TestMemUse(t *testing.T) {
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
var start, end runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&start)
memUse()
runtime.ReadMemStats(&end)
alloc := end.TotalAlloc - start.TotalAlloc
limit := uint64(64 * 1000)
if alloc > limit {
t.Error("memUse:", "allocated", alloc, "limit", limit)
}
}
:
$ go test
--- FAIL: TestMemUse (0.00s)
mem_test.go:18: memUse: allocated 65536 limit 64000
FAIL
exit status 1
FAIL mem 0.003s