Debian Codegraph @

src/testing/allocs.go

raw
1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package testing
6
7 import (
8 "runtime"
9 )
10
11 // AllocsPerRun returns the average number of allocations during calls to f.
12 // Although the return value has type float64, it will always be an integral value.
13 //
14 // To compute the number of allocations, the function will first be run once as
15 // a warm-up. The average number of allocations over the specified number of
16 // runs will then be measured and returned.
17 //
18 // AllocsPerRun sets [runtime.GOMAXPROCS] to 1 during its measurement and will restore
19 // it before returning.
20 func AllocsPerRun(runs int, f func()) (avg float64) {
21 if parallelStart.Load() != parallelStop.Load() {
22 panic("testing: AllocsPerRun called during parallel test")
23 }
24 defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
25
26 // Warm up the function
27 f()
28
29 // Measure the starting statistics
30 var memstats runtime.MemStats
31 runtime.ReadMemStats(&memstats)
32 mallocs := 0 - memstats.Mallocs
33
34 // Run the function the specified number of times
35 for i := 0; i < runs; i++ {
36 f()
37 }
38
39 // Read the final statistics
40 runtime.ReadMemStats(&memstats)
41 mallocs += memstats.Mallocs
42
43 // Average the mallocs over the runs (not counting the warm-up).
44 // We are forced to return a float64 because the API is silly, but do
45 // the division as integers so we can ask if AllocsPerRun()==1
46 // instead of AllocsPerRun()<2.
47 return float64(mallocs / uint64(runs))
48 }