基准Go代码和goroutines

nla*_*aux 0 benchmarking go goroutine

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

没有goroutines:

var t1 = time.Now()
test()
var elapsed1 = time.Since(t1)
Run Code Online (Sandbox Code Playgroud)

1 ns /操作

使用goroutines:

runtime.GOMAXPROCS(1)
var t1 = time.Now()
go test()
var elapsed1 = time.Since(t1)
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 当我在这种情况下使用goroutines时,test()函数是否已经很好地进行了基准测试?
  • 如何达到0.001ns /操作?它看起来太快了.(2.5GHz Intel Core i7)
  • 是否使用goroutine runtime.GOMAXPROCS(n)相当于使用n个线程?

fl0*_*cke 7

您没有测量test()运行的时间,而是测量/创建新goroutine所需的时间go test().

你需要等待你的goroutine完成,例如使用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)
Run Code Online (Sandbox Code Playgroud)