使用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)字節的一個堆分配。堆棧分配對於函數來說是便宜的和本地的,所以我們不計算它們。
而不是ReportAllocs
方法可以使用-benchmem
標誌。例如,
go test -bench=. -benchmem
參考文獻:
Go: Package testing: Benchmarks
Command go: Description of testing functions
Command go: Description of testing flags
如果你真的必須圍棋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
使用-benchmem標誌(並有一定的基準)。像「自由內存」這樣的東西在Go中不是一個合適的度量標準,所以你將無法做到完全一樣。 – Volker