github.com/aclements/go-misc@v0.0.0-20240129233631-2f6ede80790c/benchcmd/main.go (about)

     1  // Copyright 2016 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  // Command benchcmd times a shell command using Go benchmark format.
     6  package main
     7  
     8  import (
     9  	"flag"
    10  	"fmt"
    11  	"os"
    12  	"os/exec"
    13  	"syscall"
    14  	"time"
    15  )
    16  
    17  func main() {
    18  	flag.Usage = func() {
    19  		fmt.Fprintf(os.Stderr, "Usage: %s [-n iters] benchname cmd...\n", os.Args[0])
    20  		flag.PrintDefaults()
    21  	}
    22  	n := flag.Int("n", 5, "iterations")
    23  	flag.Parse()
    24  	if flag.NArg() < 2 {
    25  		flag.Usage()
    26  		os.Exit(2)
    27  	}
    28  	benchname := flag.Arg(0)
    29  	args := flag.Args()[1:]
    30  
    31  	for i := 0; i < *n; i++ {
    32  		cmd := exec.Command(args[0], args[1:]...)
    33  		cmd.Stdout = os.Stdout
    34  		cmd.Stderr = os.Stderr
    35  		before := time.Now()
    36  		if err := cmd.Run(); err != nil {
    37  			fmt.Println(err)
    38  			os.Exit(1)
    39  		}
    40  		after := time.Now()
    41  		fmt.Printf("Benchmark%s\t", benchname)
    42  		fmt.Printf("%d\t%d ns/op", 1, after.Sub(before))
    43  		fmt.Printf("\t%d user-ns/op\t%d sys-ns/op", cmd.ProcessState.UserTime(), cmd.ProcessState.SystemTime())
    44  		if ru, ok := cmd.ProcessState.SysUsage().(*syscall.Rusage); ok {
    45  			fmt.Printf("\t%d peak-RSS-bytes", ru.Maxrss*(1<<10))
    46  		}
    47  		fmt.Printf("\n")
    48  	}
    49  }