Source file src/testing/example_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_test
     6  
     7  import (
     8  	"math/rand/v2"
     9  	"testing"
    10  )
    11  
    12  // ExBenchmark shows how to use b.Loop in a benchmark.
    13  //
    14  // (If this were a real benchmark, not an example, this would be named
    15  // BenchmarkSomething.)
    16  func ExBenchmark(b *testing.B) {
    17  	// Generate a large random slice to use as an input.
    18  	// Since this is done before the first call to b.Loop(),
    19  	// it doesn't count toward the benchmark time.
    20  	input := make([]int, 128<<10)
    21  	for i := range input {
    22  		input[i] = rand.Int()
    23  	}
    24  
    25  	// Perform the benchmark.
    26  	for b.Loop() {
    27  		// Normally, the compiler would be allowed to optimize away the call
    28  		// to sum because it has no side effects and the result isn't used.
    29  		// However, inside a b.Loop loop, the compiler ensures function calls
    30  		// aren't optimized away.
    31  		sum(input)
    32  	}
    33  
    34  	// Outside the loop, the timer is stopped, so we could perform
    35  	// cleanup if necessary without affecting the result.
    36  }
    37  
    38  func sum(data []int) int {
    39  	total := 0
    40  	for _, value := range data {
    41  		total += value
    42  	}
    43  	return total
    44  }
    45  
    46  func ExampleB_Loop() {
    47  	testing.Benchmark(ExBenchmark)
    48  }
    49  

View as plain text