nla*_*aux 0 benchmarking go goroutine
我想对一个函数进行基准测试:test()使用不同数量的线程来处理它.
var t1 = time.Now()
test()
var elapsed1 = time.Since(t1)
Run Code Online (Sandbox Code Playgroud)
1 ns /操作
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)
runtime.GOMAXPROCS(n)相当于使用n个线程?您没有测量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)
| 归档时间: |
|
| 查看次数: |
1185 次 |
| 最近记录: |