为了账号安全,请及时绑定邮箱和手机立即绑定

基准 Go 代码和 goroutines

基准 Go 代码和 goroutines

Go
慕尼黑8549860 2021-12-07 18:49:26
我想对一个函数进行基准测试: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 个线程?
查看完整描述

2 回答

?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

您不是在测量test()运行时间,而是在测量使用go test().


您需要等待 goroutine(s) 完成,例如使用sync.Waitgroup。


// somewhere in your main package

var wg sync.WaitGroup


func test() {

   // first lines in test() should be

   wg.Add(1)

   defer wg.Done()

   ...

}



// benchmark

runtime.GOMAXPROCS(1)

var t1 = time.Now()

go test()

wg.Wait()

var elapsed1 = time.Since(t1)


查看完整回答
反对 回复 2021-12-07
?
精慕HU

TA贡献1845条经验 获得超8个赞

您正在尝试对如此小的东西进行基准测试,以至于测量误差占主导地位。您的基准测试迭代应该进行调整,直到基准测试功能持续足够长的时间才能可靠地计时。您的基准测试应该运行大约一秒钟才能有意义。


查看完整回答
反对 回复 2021-12-07
  • 2 回答
  • 0 关注
  • 138 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信