【问题标题】:How can i limit/gate memory usage in go unit test如何在 go 单元测试中限制/门控内存使用
【发布时间】:2017-02-20 20:45:15
【问题描述】:

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

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

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

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

Assert.AssertTrue(before-after < 100)

(大致)断言我们使用的字节数不超过 100 个。

【问题讨论】:

  • 使用 -benchmem 标志(并有一些基准)。像“空闲内存”这样的东西在 Go 中不是一个合适的指标,所以你无法做到完全相同。

标签: unit-testing testing memory go


【解决方案1】:

使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 2015-11-29
    相关资源
    最近更新 更多