基准 Go 代码和 goroutines

我想对一个函数进行基准测试:test(),使用不同数量的线程处理它。


没有 goroutines:

var t1 = time.Now()

test()

var elapsed1 = time.Since(t1)

1 纳秒/操作


使用 goroutine:

runtime.GOMAXPROCS(1)

var t1 = time.Now()

go test()

var elapsed1 = time.Since(t1)

1.10^-6 ns / 操作


我的测试功能:

func test() {

    for i := 0; i < 1000000000; i++ {

        float_result = f1 + f2

        float_result = f1 - f2

        float_result = f1 * f2

        float_result = f1 / f2

        float_result = f1 + f2

        float_result = f1 - f2

        float_result = f1 * f2

        float_result = f1 / f2

        float_result = f1 + f2

        float_result = f1 - f2

        float_result = f1 * f2

        float_result = f1 / f2

        float_result = f1 + f2

        float_result = f1 - f2

        float_result = f1 * f2

        float_result = f1 / f2

        float_result = f1 + f2

        float_result = f1 - f2

        float_result = f1 * f2

        float_result = f1 / f2

    }

}

在这种情况下,当我使用 goroutine 时,test() 函数是否经过良好的基准测试?

怎么可能达到0.001ns/操作?看起来速度太快了。(2.5GHz 英特尔酷睿 i7)

使用 goroutine 是否runtime.GOMAXPROCS(n)等同于使用 n 个线程?


慕尼黑8549860
浏览 141回答 2
2回答

慕田峪9158850

您不是在测量test()运行时间,而是在测量使用go test().您需要等待 goroutine(s) 完成,例如使用sync.Waitgroup。// somewhere in your main packagevar wg sync.WaitGroupfunc test() {&nbsp; &nbsp;// first lines in test() should be&nbsp; &nbsp;wg.Add(1)&nbsp; &nbsp;defer wg.Done()&nbsp; &nbsp;...}// benchmarkruntime.GOMAXPROCS(1)var t1 = time.Now()go test()wg.Wait()var elapsed1 = time.Since(t1)

精慕HU

您正在尝试对如此小的东西进行基准测试,以至于测量误差占主导地位。您的基准测试迭代应该进行调整,直到基准测试功能持续足够长的时间才能可靠地计时。您的基准测试应该运行大约一秒钟才能有意义。
打开App,查看更多内容
随时随地看视频慕课网APP