Goroutines的基准

时间:2019-02-22 00:38:17

标签: go benchmarking goroutine

这里是Golang的新手,在使用goroutine进行基准测试时遇到了问题。

我的代码在这里:

    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

     

通过

我还注意到,如果我多次向writeSpan添加一个内部循环,则运行时和分配类型与numGoroutines * multiple times有关。如果这不是人们使用goroutine进行基准测试的方式,是否还有其他标准测试方法?预先感谢。

1 个答案:

答案 0 :(得分:5)

无意义的微基准测试将产生毫无意义的结果。


  

如果这不是人们使用goroutine进行基准测试的方式,那有没有   还有其他标准测试方法吗?

这不是基准测试的方法。对实际问题进行基准测试。

您运行了大量的goroutine,这些操作什么都不做,直到您使调度程序,机器和其他资源饱和为止。那只是证明,如果您运行足够的次数,就可以使机器屈膝。