duanjuda5789 2019-02-22 00:38
浏览 43

Goroutines的基准

Pretty new to the Golang here and bumped into a problem when benchmarking with goroutines.

The code I have is here:

    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)
    }

It looks to me the runtime and allocation for both scenario should be similar, but running them gives me the following results which are vastly different. Wonder why this happens? Where do those extra allocations come from?

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

I also notice If I add a inner loop to writeSpan multiple times, the runtime and allocation kind of relates to the numGoroutines * multiple times. If this is not the way how people benchmark with goroutines, are there any other standard ways to test? Thanks in advance.

  • 写回答

1条回答 默认 最新

  • douye4051 2019-02-22 01:54
    关注

    Meaningless microbenchmarks produce meaningless results.


    If this is not the way how people benchmark with goroutines, are there any other standard ways to test?

    It's not the way to benchmark anything. Benchmark real problems.

    You run a very large number of goroutines, which do nothing, until you saturate the scheduler, the machine, and other resources. That merely proves that if you run anything enough times you can bring a machine to its knees.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?