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.
11
// AllocsPerRun returns the average number of allocations during calls to f.
13
// To compute the number of allocations, the function will first be run once as
14
// a warm-up. The average number of allocations over the specified number of
15
// runs will then be measured and returned.
17
// AllocsPerRun sets GOMAXPROCS to 1 during its measurement and will restore
18
// it before returning.
19
func AllocsPerRun(runs int, f func()) (avg float64) {
20
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
22
// Warm up the function
25
// Measure the starting statistics
26
var memstats runtime.MemStats
27
runtime.ReadMemStats(&memstats)
28
mallocs := 0 - memstats.Mallocs
30
// Run the function the specified number of times
31
for i := 0; i < runs; i++ {
35
// Read the final statistics
36
runtime.ReadMemStats(&memstats)
37
mallocs += memstats.Mallocs
39
// Average the mallocs over the runs (not counting the warm-up)
40
return float64(mallocs) / float64(runs)