这段代码(playground link):
package main
import (
"fmt"
"testing"
)
var test = make([]int, 0)
func main() {
fmt.Println(testing.Benchmark(testThis))
}
func testThis(b *testing.B) {
fmt.Println(test)
}
有下一个输出:
[]
[]
[]
[]
[]
[]
2000000000 0.00 ns/op
Program exited.
为什么输出里面有六个[]
?
这段代码(playground link):
package main
import (
"fmt"
)
var test = make([]int, 0)
func main() {
fmt.Println(test)
}
有单一输出(这对我来说很清楚):
[]
Program exited.
最佳答案
您正在使用基准函数。这需要多次执行代码才能得到一个有意义的结果。
您的基准测试也没有实现,就像基准测试应该被编程一样:
The benchmark function must run the target code b.N times. During benchmark execution, b.N is adjusted until the benchmark function lasts long enough to be timed reliably. -- https://golang.org/pkg/testing/
因此 Benchmark 将检查运行时间并调整 b.N 以获得良好且有用的基准。
当你打印 b.N 时,你会得到这样的输出:
1
100
10000
1000000
100000000
2000000000
2000000000
因此,在 6 次迭代中的每一次中,基准测试都会告诉您运行 foor 循环 b.N 次。
遗憾的是,您无法在 Playground 上使用正确的示例,因为它们需要很长时间。但正确的是:
func testThis(b *testing.B) {
for i := 0; i < b.N; i++ {
fmt.Println(test)
}
}
关于go - 为什么 Benchmark 运行六(?)次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52030137/