|
| 1 | +// Copyright 2024 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 | +func TestBenchmarkBLoop(t *T) { |
| 8 | + var initialStart highPrecisionTime |
| 9 | + var firstStart highPrecisionTime |
| 10 | + var lastStart highPrecisionTime |
| 11 | + runs := 0 |
| 12 | + iters := 0 |
| 13 | + finalBN := 0 |
| 14 | + bRet := Benchmark(func(b *B) { |
| 15 | + initialStart = b.start |
| 16 | + runs++ |
| 17 | + for b.Loop() { |
| 18 | + if iters == 0 { |
| 19 | + firstStart = b.start |
| 20 | + } |
| 21 | + lastStart = b.start |
| 22 | + iters++ |
| 23 | + } |
| 24 | + finalBN = b.N |
| 25 | + }) |
| 26 | + // Verify that a b.Loop benchmark is invoked just once. |
| 27 | + if runs != 1 { |
| 28 | + t.Errorf("want runs == 1, got %d", runs) |
| 29 | + } |
| 30 | + // Verify that at least one iteration ran. |
| 31 | + if iters == 0 { |
| 32 | + t.Fatalf("no iterations ran") |
| 33 | + } |
| 34 | + // Verify that b.N, bRet.N, and the b.Loop() iteration count match. |
| 35 | + if finalBN != iters || bRet.N != iters { |
| 36 | + t.Errorf("benchmark iterations mismatch: %d loop iterations, final b.N=%d, bRet.N=%d", iters, finalBN, bRet.N) |
| 37 | + } |
| 38 | + // Make sure the benchmark ran for an appropriate amount of time. |
| 39 | + if bRet.T < benchTime.d { |
| 40 | + t.Fatalf("benchmark ran for %s, want >= %s", bRet.T, benchTime.d) |
| 41 | + } |
| 42 | + // Verify that the timer is reset on the first loop, and then left alone. |
| 43 | + if firstStart == initialStart { |
| 44 | + t.Errorf("b.Loop did not reset the timer") |
| 45 | + } |
| 46 | + if lastStart != firstStart { |
| 47 | + t.Errorf("timer was reset during iteration") |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +// See also TestBenchmarkBLoop* in other files. |
0 commit comments