Benchmark 函数名称后的“-6”是什么意思?

What does the "-6" after the name of a Benchmark function mean?

我有一个 go 测试文件,我在其中编写了一个基准函数,如下所示:

func BenchmarkStuff(b *testing.B) {
    for i := 0; i < b.N; i++ {
        stuff()
    }
}

当我用 go test -benchtime 1x 运行 时,我得到这个:

BenchmarkStuff-6               1     847751900 ns/op

-6 是什么意思?这似乎不必要地神秘。

它表示用于 运行 基准的 CPU 的数量 - 因此在您的情况下 6.


编辑:

Go 网站上似乎没有正式记录基准名称格式,但您可以在标准库源代码中看到名称是如何制定的 here and here:

runtime.GOMAXPROCS(procs)
benchName := benchmarkName(b.name, procs)

func benchmarkName(name string, n int) string {
    if n != 1 {
        return fmt.Sprintf("%s-%d", name, n)
    }
    return name
}

仅供参考:来自 go help 命令行文档:

go help testflag
    -cpu 1,2,4
        Specify a list of GOMAXPROCS values for which the tests or
        benchmarks should be executed. The default is the current value
        of GOMAXPROCS.

因此,如果您想强制基准测试使用较少数量的 CPU,请使用环境变量 GOMAXPROCS:

$ GOMAXPROCS=2  go test -bench=.

...

BenchmarkStuff-2    1000000000           0.2642 ns/op

或者您可以像这样对多个 CPU 核心设置进行基准测试:

$ go test -bench=. -cpu=1,2,4

...

BenchmarkStuff      1000000000           0.2516 ns/op
BenchmarkStuff-2    1000000000           0.2531 ns/op
BenchmarkStuff-4    1000000000           0.2488 ns/op