...

Source file src/go/format/benchmark_test.go

Documentation: go/format

		 1  // Copyright 2018 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  // This file provides a simple framework to add benchmarks
		 6  // based on generated input (source) files.
		 7  
		 8  package format_test
		 9  
		10  import (
		11  	"bytes"
		12  	"flag"
		13  	"fmt"
		14  	"go/format"
		15  	"os"
		16  	"testing"
		17  )
		18  
		19  var debug = flag.Bool("debug", false, "write .src files containing formatting input; for debugging")
		20  
		21  // array1 generates an array literal with n elements of the form:
		22  //
		23  // var _ = [...]byte{
		24  // 	// 0
		25  // 	0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
		26  // 	0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
		27  // 	0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
		28  // 	0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
		29  // 	0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
		30  // 	// 40
		31  // 	0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
		32  // 	0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
		33  // 	...
		34  //
		35  func array1(buf *bytes.Buffer, n int) {
		36  	buf.WriteString("var _ = [...]byte{\n")
		37  	for i := 0; i < n; {
		38  		if i%10 == 0 {
		39  			fmt.Fprintf(buf, "\t// %d\n", i)
		40  		}
		41  		buf.WriteByte('\t')
		42  		for j := 0; j < 8; j++ {
		43  			fmt.Fprintf(buf, "0x%02x, ", byte(i))
		44  			i++
		45  		}
		46  		buf.WriteString("\n")
		47  	}
		48  	buf.WriteString("}\n")
		49  }
		50  
		51  var tests = []struct {
		52  	name string
		53  	gen	func(*bytes.Buffer, int)
		54  	n		int
		55  }{
		56  	{"array1", array1, 10000},
		57  	// add new test cases here as needed
		58  }
		59  
		60  func BenchmarkFormat(b *testing.B) {
		61  	var src bytes.Buffer
		62  	for _, t := range tests {
		63  		src.Reset()
		64  		src.WriteString("package p\n")
		65  		t.gen(&src, t.n)
		66  		data := src.Bytes()
		67  
		68  		if *debug {
		69  			filename := t.name + ".src"
		70  			err := os.WriteFile(filename, data, 0660)
		71  			if err != nil {
		72  				b.Fatalf("couldn't write %s: %v", filename, err)
		73  			}
		74  		}
		75  
		76  		b.Run(fmt.Sprintf("%s-%d", t.name, t.n), func(b *testing.B) {
		77  			b.SetBytes(int64(len(data)))
		78  			b.ReportAllocs()
		79  			b.ResetTimer()
		80  			for i := 0; i < b.N; i++ {
		81  				var err error
		82  				sink, err = format.Source(data)
		83  				if err != nil {
		84  					b.Fatal(err)
		85  				}
		86  			}
		87  		})
		88  	}
		89  }
		90  
		91  var sink []byte
		92  

View as plain text