codekingpro/portable-devtools
114k
1// Copyright 2018 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4 5// This file provides a simple framework to add benchmarks6// based on generated input (source) files.7 8package format_test9 10import (11 "bytes"12 "flag"13 "fmt"14 "go/format"15 "os"16 "testing"17)18 19var 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// // 025// 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// // 4031// 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,32// 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,33// ...34func array1(buf *bytes.Buffer, n int) {35 buf.WriteString("var _ = [...]byte{\n")36 for i := 0; i < n; {37 if i%10 == 0 {38 fmt.Fprintf(buf, "\t// %d\n", i)39 }40 buf.WriteByte('\t')41 for j := 0; j < 8; j++ {42 fmt.Fprintf(buf, "0x%02x, ", byte(i))43 i++44 }45 buf.WriteString("\n")46 }47 buf.WriteString("}\n")48}49 50var tests = []struct {51 name string52 gen func(*bytes.Buffer, int)53 n int54}{55 {"array1", array1, 10000},56 // add new test cases here as needed57}58 59func BenchmarkFormat(b *testing.B) {60 var src bytes.Buffer61 for _, t := range tests {62 src.Reset()63 src.WriteString("package p\n")64 t.gen(&src, t.n)65 data := src.Bytes()66 67 if *debug {68 filename := t.name + ".src"69 err := os.WriteFile(filename, data, 0660)70 if err != nil {71 b.Fatalf("couldn't write %s: %v", filename, err)72 }73 }74 75 b.Run(fmt.Sprintf("%s-%d", t.name, t.n), func(b *testing.B) {76 b.SetBytes(int64(len(data)))77 b.ReportAllocs()78 b.ResetTimer()79 for i := 0; i < b.N; i++ {80 var err error81 sink, err = format.Source(data)82 if err != nil {83 b.Fatal(err)84 }85 }86 })87 }88}89 90var sink []byte91 