github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/brutecheck/bench/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  
     7  	"github.com/loov/hrtime"
     8  	"gonum.org/v1/gonum/stat"
     9  )
    10  
    11  var Valid = []string{
    12  	"break", "case", "chan", "const", "continue",
    13  	"default", "defer", "else", "fallthrough", "for", "func", "go",
    14  	"goto", "if", "import", "interface", "map", "package", "range", "return",
    15  	"select", "struct", "switch", "type", "var",
    16  }
    17  
    18  func main() {
    19  	runtime.LockOSThread()
    20  
    21  	const repeat = 20000
    22  	const rounds = 20
    23  
    24  	type result struct {
    25  		name string
    26  		ns   [rounds]float64
    27  	}
    28  
    29  	results := make([]result, len(AllBenches))
    30  	for i, bench := range AllBenches {
    31  		results[i].name = bench.Name
    32  	}
    33  
    34  	for round := 0; round < rounds; round++ {
    35  		for i, bench := range AllBenches {
    36  			fn := bench.Fn
    37  			fn(Valid, 1)
    38  
    39  			start := hrtime.TSC()
    40  			fn(Valid, repeat)
    41  			finish := hrtime.TSC()
    42  
    43  			totalns := float64((finish - start).ApproxDuration().Nanoseconds())
    44  			avgns := totalns / float64(repeat*len(Valid))
    45  
    46  			results[i].ns[round] = avgns
    47  		}
    48  	}
    49  
    50  	fmt.Printf("func,mean,stddev")
    51  	for round := 0; round < rounds; round++ {
    52  		fmt.Printf(",#%d ns", round)
    53  	}
    54  	fmt.Println()
    55  
    56  	for _, r := range results {
    57  		fmt.Printf("%s,", r.name)
    58  		mean, stddev := stat.MeanStdDev(r.ns[:], nil)
    59  		fmt.Printf("%.2f, %.2f", mean, stddev)
    60  		for _, ns := range r.ns {
    61  			fmt.Printf(",%.2f", ns)
    62  		}
    63  		fmt.Println()
    64  	}
    65  }