2017-02-20 82 views
4

有沒有辦法來限制在單元測試中的內存使用量/增長量在golang?我怎麼能限制/門內存使用去單元測試

例如,在Java中,我們可以這樣做:

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

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

Assert.AssertTrue(before-after < 100) 

(大約)斷言,我們沒有使用超過100個字節。

+0

使用-benchmem標誌(並有一定的基準)。像「自由內存」這樣的東西在Go中不是一個合適的度量標準,所以你將無法做到完全一樣。 – Volker

回答

4

使用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 
相關問題