From 67d7568ca2b99e44855b399347dd3d6801978ea8 Mon Sep 17 00:00:00 2001 From: Respawnz <47511522+Respawnz@users.noreply.github.com> Date: Thu, 11 Jul 2019 12:28:51 +0800 Subject: [PATCH] =?UTF-8?q?14.16=20Benchmarking=20goroutines=20=E5=AF=B9Go?= =?UTF-8?q?=E5=8D=8F=E7=A8=8B=E8=BF=9B=E8=A1=8C=E5=9F=BA=E5=87=86=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=20(#633)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 --- eBook/14.16.md | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 eBook/14.16.md diff --git a/eBook/14.16.md b/eBook/14.16.md new file mode 100644 index 0000000..53dbe66 --- /dev/null +++ b/eBook/14.16.md @@ -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) + +