Source file src/testing/loop_test.go

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

View as plain text