~ubuntu-branches/ubuntu/vivid/golang/vivid

« back to all changes in this revision

Viewing changes to src/pkg/testing/allocs.go

  • Committer: Package Import Robot
  • Author(s): James Page
  • Date: 2013-08-20 14:06:23 UTC
  • mfrom: (14.1.23 saucy-proposed)
  • Revision ID: package-import@ubuntu.com-20130820140623-b414jfxi3m0qkmrq
Tags: 2:1.1.2-2ubuntu1
* Merge from Debian unstable (LP: #1211749, #1202027). Remaining changes:
  - 016-armhf-elf-header.patch: Use correct ELF header for armhf binaries.
  - d/control,control.cross: Update Breaks/Replaces for Ubuntu
    versions to ensure smooth upgrades, regenerate control file.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
//
 
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.
 
16
//
 
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))
 
21
 
 
22
        // Warm up the function
 
23
        f()
 
24
 
 
25
        // Measure the starting statistics
 
26
        var memstats runtime.MemStats
 
27
        runtime.ReadMemStats(&memstats)
 
28
        mallocs := 0 - memstats.Mallocs
 
29
 
 
30
        // Run the function the specified number of times
 
31
        for i := 0; i < runs; i++ {
 
32
                f()
 
33
        }
 
34
 
 
35
        // Read the final statistics
 
36
        runtime.ReadMemStats(&memstats)
 
37
        mallocs += memstats.Mallocs
 
38
 
 
39
        // Average the mallocs over the runs (not counting the warm-up)
 
40
        return float64(mallocs) / float64(runs)
 
41
}