我想对一个函数进行基准测试: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/