How can I limit the use of shutter memory in go unit test

Is there a way to limit the amount of memory usage / growth during unit test in golang?

For example, in java we can do:

long before = Runtime.getRuntime().freeMemory()

// allocate a bunch of memory
long after = Runtime.getRuntime().freeMemory()

Assert.AssertTrue(before-after < 100)

(roughly) to claim that we did not use more than 100 bytes.

+4
source share
1 answer

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
+4

Source: https://habr.com/ru/post/1670337/


All Articles