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
パッケージのテストFUNCT時のメモリ制限を適用する必要がある場合イオン、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