go - 基准 Go 代码和 goroutines

标签 go benchmarking goroutine

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

没有协程:

var t1 = time.Now()
test()
var elapsed1 = time.Since(t1)

1 ns / operation

使用协程:

runtime.GOMAXPROCS(1)
var t1 = time.Now()
go test()
var elapsed1 = time.Since(t1)

1.10^-6 ns / operation

我的测试函数:

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.001 纳秒/操作?它看起来太快了。 (2.5GHz 英特尔酷睿 i7)
  • 使用带有 runtime.GOMAXPROCS(n) 的 goroutine 是否等同于使用 n 个线程?

最佳答案

您测量的不是 test() 运行的时间,而是使用 go test() 调用/创建新 goroutine 所花费的时间。

您需要等待您的 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)

关于go - 基准 Go 代码和 goroutines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35231859/

相关文章:

arrays - Golang 创建 bytes.Buffer 数组的多读取器

linux - 如何使用 Go 在 Linux 中检查文件的权限

java - Guava 缓存与 ehcache 基准测试

go - 为什么没有接收器被阻塞的错误?

go - go中的dialogflow webhook

rest - golang gin-gonic 和包中的拆分文件

java - 基于基准的最快/内存/大小高效的 Java 序列化框架是什么?

java - 规范jvm : How to execute outside installation folder

memory - 进程和Golang中的Goroutine一样吗?

arrays - Golang 字节数组通过 channel 通信丢失数据