【发布时间】:2016-02-05 19:20:57
【问题描述】:
我想对一个函数进行基准测试:test(),使用不同数量的线程处理它。
没有 goroutine:
var t1 = time.Now()
test()
var elapsed1 = time.Since(t1)
1 ns / 操作
使用 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)
- 使用带有
runtime.GOMAXPROCS(n)的goroutines 是否等同于使用n 个线程?
【问题讨论】:
-
任何语言的任何体面的编译器都会丢弃循环中的几乎所有代码,因为您的 float_result 值从未使用过。您需要将其写入输出或文件。
-
即使你在最后使用了 float_result,也只有最后一行会运行,因为所有其他行都被覆盖了。
-
我想做很多操作,不多次使用同一个变量怎么办?如果我做var = f1 + f2 + f3 + f4,编译后直接写f1 + f2 + f3 + f4的值,不行吗?
标签: go benchmarking goroutine