golang 基准测试可以提供自定义输出吗?

Can golang benchmark give a custom output?

我正在对具有不同列表大小(大小为 S 的列表)的代码进行基准测试 Go 基准显示 ns/op 但我想要的是 (ns/op)/S.

也就是说go test -bench=.的输出是:

BenchmarkMy10-4         100000000           15.7 ns/op
BenchmarkMy20-4         50000000            33.8 ns/op
BenchmarkMy30-4         30000000            43.8 ns/op
BenchmarkMy40-4         30000000            49.3 ns/op
BenchmarkMy50-4         30000000            56.6 ns/op
BenchmarkMy1000-4        2000000           686 ns/op
BenchmarkMy10000-4        200000          6685 ns/op
BenchmarkMy100000-4        20000         65425 ns/op

"My10" 中的“10”表示包含 10 个项目的列表 (S=10)。

虽然了解不同列表大小的 ns/op 很有用,但我还想知道 ns/op/S(列表中每个项目的时间)。

现在我正在将结果粘贴到电子表格中并在那里进行计算。但是我想让 "go test" 为我输出这些信息。

我的 main_test.go 文件如下所示:

import "testing"

var result int

func benchmarkMy(i int, b *testing.B) {
  var r int
  mylist := MakeList(i)
  b.ResetTimer()
  for n := 0; n < b.N; n++ {
    r = My(mylist)
  }
  result = r
}

func BenchmarkMy10(b *testing.B)         { benchmarkMy(10, b) }
func BenchmarkMy20(b *testing.B)         { benchmarkMy(20, b) }
func BenchmarkMy30(b *testing.B)         { benchmarkMy(30, b) }
func BenchmarkMy40(b *testing.B)         { benchmarkMy(40, b) }
func BenchmarkMy50(b *testing.B)         { benchmarkMy(50, b) }
func BenchmarkMy1000(b *testing.B)       { benchmarkMy(1000, b) }
func BenchmarkMy10000(b *testing.B)      { benchmarkMy(10000, b) }
func BenchmarkMy100000(b *testing.B)     { benchmarkMy(100000, b) }

test.BenchmarkResult结构似乎有我需要的信息,但我不知道如何使用这个结构。

您可以使用包 testing 中的 Benchmark 函数编写自定义基准测试。并得到一个你提到的 BenchmarkResult 实例。

package main

import (
    "fmt"
    "testing"
)

func benchmarkMy(i int) {
    fn := func(b *testing.B) {
         // Code you want benchmarked
    }
    r := testing.Benchmark(fn)

    fmt.Printf("%d ns/op\n", int(r.T)/r.N)
    fmt.Printf("%d ns/op/i\n", int(r.T)/r.N/i)
}

func main() {
    benchmarkMy(10)
}

您必须将其放在不同的包中,并且 运行 使用 go run 而不是 go test

检查 playground 中的示例。