LEFT | RIGHT |
1 package testing | 1 package testing |
2 | 2 |
3 import ( | 3 import ( |
4 "runtime" | 4 "runtime" |
5 ) | 5 ) |
6 | 6 |
7 // AllocsPerRun returns the average number of allocations during calls to f. | 7 // AllocsPerRun returns the average number of allocations during calls to f. |
8 // | 8 // |
9 // To compute the number of allocations, the function will first be run once as | 9 // To compute the number of allocations, the function will first be run once as |
10 // a warm-up. The average number of allocations over the specified number of | 10 // a warm-up. The average number of allocations over the specified number of |
11 // runs will then be measured and returned. | 11 // runs will then be measured and returned. |
12 // | 12 // |
13 // AllocsPerRun sets GOMAXPROCS to 1 during its measurement and will restore | 13 // AllocsPerRun sets GOMAXPROCS to 1 during its measurement and will restore |
14 // it before returning. | 14 // it before returning. |
15 func AllocsPerRun(runs int, f func()) float64 { | 15 func AllocsPerRun(runs int, f func()) (avg float64) { |
16 defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1)) | 16 defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1)) |
17 return (&B{N: runs}).Allocs(f) | |
18 } | |
19 | |
20 // Allocs is like AllocsPerRun, but it will use b.N as the iteration count. | |
21 // The warm-up run and collection of the memory statistics will not be | |
22 // counted toward the run time of the benchmark. | |
23 func (b *B) Allocs(f func()) float64 { | |
24 b.StopTimer() | |
25 defer b.StartTimer() | |
26 | 17 |
27 // Warm up the function | 18 // Warm up the function |
28 f() | 19 f() |
29 | 20 |
30 // Measure the starting statistics | 21 // Measure the starting statistics |
31 » memstats := new(runtime.MemStats) | 22 » var memstats runtime.MemStats |
32 » runtime.ReadMemStats(memstats) | 23 » runtime.ReadMemStats(&memstats) |
33 mallocs := 0 - memstats.Mallocs | 24 mallocs := 0 - memstats.Mallocs |
34 | 25 |
35 » // Run the function b.N times | 26 » // Run the function the specified number of times |
36 » b.StartTimer() | 27 » for i := 0; i < runs; i++ { |
37 » for i := 0; i < b.N; i++ { | |
38 f() | 28 f() |
39 } | 29 } |
40 b.StopTimer() | |
41 | 30 |
42 // Read the final statistics | 31 // Read the final statistics |
43 » runtime.ReadMemStats(memstats) | 32 » runtime.ReadMemStats(&memstats) |
44 mallocs += memstats.Mallocs | 33 mallocs += memstats.Mallocs |
45 | 34 |
46 // Average the mallocs over the runs (not counting the warm-up) | 35 // Average the mallocs over the runs (not counting the warm-up) |
47 » return float64(mallocs) / float64(b.N) | 36 » return float64(mallocs) / float64(runs) |
48 } | 37 } |
LEFT | RIGHT |