testing: add AllocsPerRun

This CL also replaces similar loops in other stdlib
package tests with calls to AllocsPerRun.

Fixes #4461.

R=minux.ma, rsc
CC=golang-dev
https://golang.org/cl/7002055
This commit is contained in:
Kyle Lemons 2013-02-02 22:52:29 -05:00 committed by Russ Cox
parent f418c505d0
commit 9bfd3c3937
10 changed files with 105 additions and 144 deletions

View file

@ -13,7 +13,6 @@ import (
"math/rand"
"os"
. "reflect"
"runtime"
"sync"
"testing"
"time"
@ -2012,20 +2011,13 @@ func TestAddr(t *testing.T) {
}
func noAlloc(t *testing.T, n int, f func(int)) {
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
// once to prime everything
f(-1)
memstats := new(runtime.MemStats)
runtime.ReadMemStats(memstats)
oldmallocs := memstats.Mallocs
for j := 0; j < n; j++ {
f(j)
}
runtime.ReadMemStats(memstats)
mallocs := memstats.Mallocs - oldmallocs
if mallocs > 0 {
t.Fatalf("%d mallocs after %d iterations", mallocs, n)
i := -1
allocs := testing.AllocsPerRun(n, func() {
f(i)
i++
})
if allocs > 0 {
t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
}
}