14.16 Benchmarking goroutines 对Go协程进行基准测试 (#633)

* Create 14.16.md

* Update 14.16.md

* Update 14.16.md

* Update 14.16.md

* Update 14.16.md

* Update 14.16.md

* Update 14.16.md
This commit is contained in:
Respawnz
2019-07-11 12:28:51 +08:00
committed by ᴊ. ᴄʜᴇɴ
parent 4459fd0f17
commit 67d7568ca2

61
eBook/14.16.md Normal file
View File

@@ -0,0 +1,61 @@
# 14.16 对Go协程进行基准测试
在 [13.7 节](13.7.md) 我们提到了在Go语言中对你的函数进行基准测试。在此我们将其应用到一个用协程向通道写入整数再读出的实例中。这个函数将通过`testing.Benchmark`调用`N`次(例如:`N = 1,000,000``BenchMarkResult`有一个`String()`方法来输出其结果。`N`的值将由`gotest`来判断并取得一个足够大的数字,以获得合理的基准测试结果。当然同样的基准测试方法也适用于普通函数。
如果你想排除指定部分的代码或者更具体的指定要测试的部分,可以使用`testing.B.startTimer()``testing.B.stopTimer()`来开始或结束计时器。基准测试只有在所有的测试通过后才能运行!
示例:[14.18-benchmark_channels.go](examples/chapter_14/benchmark_channels.go)
```go
package main
import (
"fmt"
"testing"
)
func main() {
fmt.Println(" sync", testing.Benchmark(BenchmarkChannelSync).String())
fmt.Println("buffered", testing.Benchmark(BenchmarkChannelBuffered).String())
}
func BenchmarkChannelSync(b *testing.B) {
ch := make(chan int)
go func() {
for i := 0; i < b.N; i++ {
ch <- i
}
close(ch)
}()
for range ch {
}
}
func BenchmarkChannelBuffered(b *testing.B) {
ch := make(chan int, 128)
go func() {
for i := 0; i < b.N; i++ {
ch <- i
}
close(ch)
}()
for range ch {
}
}
```
输出:
```
Output:Windows: N Time 1 op Operations per sec
sync 1000000 2443 ns/op --> 409 332 / s
buffered 1000000 4850 ns/op --> 810 477 / s
Linux:
```
## 链接
- [目录](directory.md)
- 上一节:[漏桶算法](14.15.md)
- 下一节:[使用通道并发访问对象](14.17.md)