这里是 Golang 的新手,在使用 goroutines 进行基准测试时遇到了问题。
我的代码在这里:
type store struct{}
func (n *store) WriteSpan(span interface{}) error {
return nil
}
func smallTest(times int, b *testing.B) {
writer := store{}
var wg sync.WaitGroup
numGoroutines := times
wg.Add(numGoroutines)
b.ResetTimer()
b.ReportAllocs()
for n := 0; n < numGoroutines; n++ {
go func() {
writer.WriteSpan(nil)
wg.Done()
}()
}
wg.Wait()
}
func BenchmarkTest1(b *testing.B) {
smallTest(1000000, b)
}
func BenchmarkTest2(b *testing.B) {
smallTest(10000000, b)
}
在我看来,这两种情况的运行时间和分配应该相似,但运行它们会给我以下截然不同的结果。想知道为什么会这样吗?这些额外分配从何而来?
BenchmarkTest1-12 1000000000 0.26 ns/op 0 B/op 0 allocs/op
BenchmarkTest2-12 1 2868129398 ns/op 31872 B/op 83 allocs/op
PASS
我还注意到,如果我多次向 writeSpan
添加内部循环,则运行时和分配类型与 numGoroutines * 多次相关
。如果这不是人们使用 goroutines 进行基准测试的方式,还有其他标准的测试方法吗?提前致谢。
最佳答案
无意义的微基准测试产生无意义的结果。
If this is not the way how people benchmark with goroutines, are there any other standard ways to test?
这不是衡量任何东西的方法。基准真实问题。
您运行了大量的 goroutine,它们什么都不做,直到您使调度程序、机器和其他资源饱和。这仅仅证明,如果你运行任何东西足够多次,你就可以让机器瘫痪。
关于go - 使用 Goroutines 进行基准测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54818355/