go - 使用 Goroutines 进行基准测试

标签 go benchmarking goroutine

这里是 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/

相关文章:

http - Go 如何从请求 a.body 流式读取到新请求的主体

go - Gin 框架无法从 Postman 获取数据

docker cli swarm 包导入问题

apache - 如何对Apache/nginx设置进行基准测试

go - 改变合并排序中 channel 的使用会杀死我的程序;或者我在处理 goroutine 时误解了范围?

go - 如何在同一循环内向 channel 发送值或从 channel 接收值?

go - os.IsNotExist 但得到 "not a directory"

redis - Apache Geode 的基准测试

linux - 在 Docker 内部进行基准测试时消除 UnionFS 对结果的影响

go - 使用 channel 来调度任务以进行例程