github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/testing/benchmark_test.go (about) 1 // Copyright 2011 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 "testing" 9 ) 10 11 var buf = make([]byte, 13579) 12 13 func NonASCII(b []byte, i int, offset int) int { 14 for i = offset; i < len(b)+offset; i++ { 15 if b[i%len(b)] >= 0x80 { 16 break 17 } 18 } 19 return i 20 } 21 22 func BenchmarkFastNonASCII(b *testing.B) { 23 var val int 24 for i := 0; i < b.N; i++ { 25 val += NonASCII(buf, 0, 0) 26 } 27 } 28 29 func BenchmarkSlowNonASCII(b *testing.B) { 30 var val int 31 for i := 0; i < b.N; i++ { 32 val += NonASCII(buf, 0, 0) 33 val += NonASCII(buf, 0, 1) 34 } 35 } 36 37 // TestBenchmark simply uses Benchmark twice and makes sure it does not crash. 38 func TestBenchmark(t *testing.T) { 39 // FIXME: reduce runtime from the current 3 seconds. 40 rslow := testing.Benchmark(BenchmarkSlowNonASCII) 41 rfast := testing.Benchmark(BenchmarkFastNonASCII) 42 tslow := rslow.NsPerOp() 43 tfast := rfast.NsPerOp() 44 45 // Be exceedingly forgiving; do not fail even if system gets busy. 46 speedup := float64(tslow) / float64(tfast) 47 if speedup < 0.3 { 48 t.Errorf("Expected speedup >= 0.3, got %f", speedup) 49 } 50 } 51 52 func BenchmarkSub(b *testing.B) { 53 b.Run("Fast", func(b *testing.B) { BenchmarkFastNonASCII(b) }) 54 b.Run("Slow", func(b *testing.B) { BenchmarkSlowNonASCII(b) }) 55 }