Files
the-way-to-go_ZH_CN/eBook/14.16.md
Respawnz 67d7568ca2 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
2019-07-10 21:28:51 -07:00

62 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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)