From 6bd56fcaebde61eb6bd21906a7d7136d009be4a6 Mon Sep 17 00:00:00 2001 From: Austin Clements Date: Thu, 12 Dec 2024 18:19:43 -0500 Subject: testing: improve b.Loop example The current b.Loop example doesn't focus on the basic usage of b.Loop. Replace this with a new example that uses (slightly) more realistic things to demonstrate the most salient points of b.Loop. We also move the example into an example file so that we can write a real Benchmark function and a real function to be benchmarks, which makes this much closer to what a user would actually write. Updates #61515. Change-Id: I4d830b3bfe3eb3cd8cdecef469fea0541baebb43 Reviewed-on: https://go-review.googlesource.com/c/go/+/635896 Auto-Submit: Austin Clements Reviewed-by: Junyang Shao Reviewed-by: Cherry Mui LUCI-TryBot-Result: Go LUCI --- src/testing/benchmark_test.go | 30 ------------------------------ 1 file changed, 30 deletions(-) (limited to 'src/testing/benchmark_test.go') diff --git a/src/testing/benchmark_test.go b/src/testing/benchmark_test.go index b3089b3119..239e730021 100644 --- a/src/testing/benchmark_test.go +++ b/src/testing/benchmark_test.go @@ -149,36 +149,6 @@ func TestBLoopHasResults(t *testing.T) { } } -func ExampleB_Loop() { - simpleFunc := func(i int) int { - return i + 1 - } - n := 0 - testing.Benchmark(func(b *testing.B) { - // Unlike "for i := range b.N {...}" style loops, this - // setup logic will only be executed once, so simpleFunc - // will always get argument 1. - n++ - // It behaves just like "for i := range N {...}", except with keeping - // function call parameters and results alive. - for b.Loop() { - // This function call, if was in a normal loop, will be optimized away - // completely, first by inlining, then by dead code elimination. - // In a b.Loop loop, the compiler ensures that this function is not optimized away. - simpleFunc(n) - } - // This clean-up will only be executed once, so after the benchmark, the user - // will see n == 2. - n++ - // Use b.ReportMetric as usual just like what a user may do after - // b.N loop. - }) - // We can expect n == 2 here. - - // The return value of the above Benchmark could be used just like - // a b.N loop benchmark as well. -} - func ExampleB_RunParallel() { // Parallel benchmark for text/template.Template.Execute on a single object. testing.Benchmark(func(b *testing.B) { -- cgit v1.3-5-g9baa