“-6”在基准函数名称后面代表什么意思?

huangapple go评论123阅读模式
英文:

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

问题

-6 是指示性能测试的 GOMAXPROCS 值。GOMAXPROCS 是 Go 语言运行时的一个环境变量,用于设置并发执行的最大 CPU 数量。在这种情况下,-6 表示测试使用了 6 个 CPU 核心进行并发执行。这个值可以根据你的机器配置和运行时环境的不同而有所变化。

英文:

I have a go test file in which I wrote a benchmark function as follows:

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

When I run this with go test -benchtime 1x, I get this:

BenchmarkStuff-6     	       1	 847751900 ns/op

What does the -6 mean? It seems unnecessarily cryptic.

答案1

得分: 10

这段内容的翻译如下:

它表示用于运行基准测试的CPU数量-所以在你的情况下是6

编辑:

Go官方网站上似乎没有正式记录基准测试名称的格式,但你可以在标准库源代码中看到名称是如何生成的这里这里

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
}

FYI:从go help命令行文档中可以了解到:

go help testflag

    -cpu 1,2,4
        指定要执行测试或基准测试的GOMAXPROCS值的列表。默认值为当前的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
英文:

It's indicating the number of CPUs that were used to run the benchmark - so in your case 6.


EDIT:

The Benchmark name format does not appear to be formally documented on the Go website, but you can see in the standard library source how the name is formulated 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
}

FYI: from the go help command-line docs:

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.

So if you wanted to coerce your benchmarking to use a lower number of CPUs use the env var GOMAXPROCS:

$ GOMAXPROCS=2  go test -bench=.

...

BenchmarkStuff-2   	1000000000	         0.2642 ns/op

Or you can benchmark multiple CPU core settings like so:

$ 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

huangapple
  • 本文由 发表于 2021年7月20日 05:15:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/68447103.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定