gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/test/benchmarks/tools/hackbench.go (about)

     1  // Copyright 2022 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //	http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package tools
    16  
    17  import (
    18  	"fmt"
    19  	"regexp"
    20  	"strconv"
    21  	"testing"
    22  )
    23  
    24  // Hackbench makes 'hackbench' commands and parses their output.
    25  type Hackbench struct {
    26  	IpcMode     string // ipc mode: pipe, socket(default)
    27  	ProcessMode string // process mode: thread, process(default)
    28  }
    29  
    30  // MakeCmd makes commands for Hackbench.
    31  func (s *Hackbench) MakeCmd(b *testing.B) []string {
    32  	cmd := []string{"hackbench"}
    33  	// ipc mode
    34  	if s.IpcMode == "pipe" {
    35  		cmd = append(cmd, "--pipe")
    36  	}
    37  	// group num
    38  	cmd = append(cmd, "--groups=10")
    39  	// process mode
    40  	if s.ProcessMode == "thread" {
    41  		cmd = append(cmd, "--threads")
    42  	} else {
    43  		cmd = append(cmd, "--process")
    44  	}
    45  	// loops
    46  	cmd = append(cmd, fmt.Sprintf("--loops=%d", b.N))
    47  	return cmd
    48  }
    49  
    50  // Report reports the relevant metrics for Hackbench.
    51  func (s *Hackbench) Report(b *testing.B, output string) {
    52  	b.Helper()
    53  	result, err := s.parseResult(output)
    54  	if err != nil {
    55  		b.Fatalf("parsing result from %s failed: %v", output, err)
    56  	}
    57  	ReportCustomMetric(b, result, "execution_time" /*metric name*/, "s" /*unit*/)
    58  	ReportCustomMetric(b, result/float64(b.N), "execution_time_per_loop" /*metric name*/, "s" /*unit*/)
    59  }
    60  
    61  var hackbenchRegexp = regexp.MustCompile(`Time:\s*(\d*.?\d*)\n`)
    62  
    63  func (s *Hackbench) parseResult(data string) (float64, error) {
    64  	match := hackbenchRegexp.FindStringSubmatch(data)
    65  	if len(match) < 2 {
    66  		return 0.0, fmt.Errorf("could not find Time: %s", data)
    67  	}
    68  	return strconv.ParseFloat(match[1], 64)
    69  }