github.com/consensys/gnark-crypto@v0.14.0/internal/bench/main.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io/fs"
     7  	"log"
     8  	"os"
     9  	"os/exec"
    10  	"path/filepath"
    11  	"strconv"
    12  	"strings"
    13  )
    14  
    15  type entry struct {
    16  	entry fs.DirEntry
    17  	path  string
    18  }
    19  
    20  func main() {
    21  	// quick and dirty helper to benchmark field elements across branches
    22  
    23  	var entries []entry
    24  	err := filepath.WalkDir("../../ecc", func(path string, d fs.DirEntry, err error) error {
    25  		if d.IsDir() {
    26  			if d.Name() == "fp" || d.Name() == "fr" {
    27  				entries = append(entries, entry{entry: d, path: path})
    28  			}
    29  		}
    30  		return nil
    31  	})
    32  
    33  	if err != nil {
    34  		log.Fatal(err)
    35  	}
    36  
    37  	const benchCount = 10
    38  	const regexp = "ElementSqrt"
    39  	const refBranch = "developt"
    40  	const newBranch = "feat-addchain"
    41  
    42  	var buf bytes.Buffer
    43  	runBenches := func(branch string) {
    44  		checkout(branch)
    45  		for _, e := range entries {
    46  			buf.Reset()
    47  			count := strconv.Itoa(benchCount)
    48  			cmd := exec.Command("go", "test", "-timeout", "10m", "-run", "^$", "-bench", regexp, "-count", count)
    49  			args := strings.Join(cmd.Args, " ")
    50  			log.Println("running benchmark", "dir", e.path, "cmd", args)
    51  			cmd.Dir = e.path
    52  			cmd.Env = os.Environ()
    53  			cmd.Env = append(cmd.Env, "CGO_ENABLED=0")
    54  			cmd.Stdout = &buf
    55  			cmd.Stderr = os.Stderr
    56  			err := cmd.Run()
    57  			if err != nil {
    58  				log.Fatal(err)
    59  			}
    60  
    61  			if err := os.WriteFile(filepath.Join(e.path, branch+".txt"), buf.Bytes(), 0600); err != nil {
    62  				log.Fatal(err)
    63  			}
    64  		}
    65  	}
    66  
    67  	runBenches(refBranch)
    68  	runBenches(newBranch)
    69  
    70  	for _, e := range entries {
    71  		fmt.Println()
    72  		log.Println("comparing", e.path, regexp)
    73  		cmd := exec.Command("benchstat", "-alpha", "2.0", refBranch+".txt", newBranch+".txt")
    74  		cmd.Dir = e.path
    75  		cmd.Stdout = os.Stdout
    76  		cmd.Stderr = os.Stderr
    77  		err := cmd.Run()
    78  		if err != nil {
    79  			log.Fatal(err)
    80  		}
    81  		fmt.Println()
    82  	}
    83  }
    84  
    85  func checkout(branch string) {
    86  	cmd := exec.Command("git", "checkout", branch)
    87  	cmd.Stdout = os.Stdout
    88  	cmd.Stderr = os.Stderr
    89  	err := cmd.Run()
    90  	if err != nil {
    91  		log.Fatal(err)
    92  	}
    93  }