我如何在 go 单元测试中限制/门内存使用

jay*_*100 4 memory testing unit-testing go

在 golang 单元测试期间,有没有办法限制内存使用量/增长量?

例如,在java中,我们可以这样做:

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

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

Assert.AssertTrue(before-after < 100)
Run Code Online (Sandbox Code Playgroud)

(粗略地)断言我们没有使用超过 100 个字节。

pet*_*rSO 5

Use Go benchmarks to analyze memory usage. For example:

mem.go:

package mem

func memUse() {
    var stack [1024]byte
    heap := make([]byte, 64*1024)
    _, _ = stack, heap
}
Run Code Online (Sandbox Code Playgroud)

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()
}
Run Code Online (Sandbox Code Playgroud)

Output:

$ 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
Run Code Online (Sandbox Code Playgroud)

The memUse function makes one heap allocation of 65536 (64*1024) bytes. Stack allocations are cheap and local to a function so we don't count them.

Instead of the ReportAllocs method you could use the -benchmem flag. For example,

go test -bench=. -benchmem
Run Code Online (Sandbox Code Playgroud)

References:

Go: Package testing: Benchmarks

Command go: Description of testing functions

Command go: Description of testing flags


If you really must apply a memory limit during a Go testing package Test function, try using runtime.MemStats. For example,

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

Output:

$ go test
--- FAIL: TestMemUse (0.00s)
    mem_test.go:18: memUse: allocated 65536 limit 64000
FAIL
exit status 1
FAIL    mem 0.003s
Run Code Online (Sandbox Code Playgroud)