使用 Go 基准来分析内存使用情况。例如:
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()
}
输出:
$ 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
memUse 函数分配了一个 65536 (64*1024) 字节的堆。堆栈分配对于函数来说很便宜并且是本地的,所以我们不计算它们。
您可以使用-benchmem 标志来代替ReportAllocs 方法。例如,
go test -bench=. -benchmem
参考资料:
Go: Package testing: Benchmarks
Command go: Description of testing functions
Command go: Description of testing flags
如果您确实必须在 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