GO中的基准测试是通过testing
软件包来促进的,该软件包提供了一种简单而强大的方法来测量代码的性能。要编写基准测试,请使用Benchmark
功能前缀,然后使用一个描述基准测试的名称。这是如何编写基准的基本示例:
<code class="go">package main import "testing" func BenchmarkMyFunction(b *testing.B) { for i := 0; i </code>
在此示例中, bN
是测试包设置的数字,该数字指示应运行该功能的次数。测试包将调整bN
以获得准确的测量。
要运行基准测试,您将使用-bench
标志的go test
命令。例如:
<code class="bash">go test -bench=BenchmarkMyFunction</code>
该命令将运行基准并输出结果,显示每个操作所花费的时间。
在GO中编写有效的基准涉及几种最佳实践,以确保准确有意义的结果:
使用b.ResetTimer()
:如果您需要在实际基准之前执行设置操作,请使用b.ResetTimer()
在设置后和实际基准代码之前重置计时器。
<code class="go">func BenchmarkMyFunction(b *testing.B) { // Setup code b.ResetTimer() for i := 0; i </code>
使用b.StopTimer()
和b.StartTimer()
:如果您需要执行不应包含在基准中的操作,则可以停止并围绕这些操作启动计时器。
<code class="go">func BenchmarkMyFunction(b *testing.B) { for i := 0; i </code>
多次运行基准测试:使用-count
标志多次运行基准测试以说明可变性。
<code class="bash">go test -bench=BenchmarkMyFunction -count=5</code>
使用b.ReportAllocs()
:要测量内存分配,请在基准功能开始时使用b.ReportAllocs()
。
<code class="go">func BenchmarkMyFunction(b *testing.B) { b.ReportAllocs() for i := 0; i </code>
分析和解释基准结果GO涉及了解go test
命令提供的输出。这是解释典型输出的方法:
<code class="bash">BenchmarkMyFunction-8 1000000 123 ns/op</code>
bN
)基准运行。更深入地分析结果:
使用-benchmem
标志:此标志提供内存分配统计信息。
<code class="bash">go test -bench=BenchmarkMyFunction -benchmem</code>
输出可能看起来像这样:
<code class="bash">BenchmarkMyFunction-8 1000000 123 ns/op 16 B/op 1 allocs/op</code>
benchstat
工具可以帮助比较代码的不同运行或版本的基准结果。几种工具可以增强GO测试包提供的基准功能:
台面:GO团队的工具,有助于比较不同运行的基准结果。可以使用以下方式安装:
<code class="bash">go get golang.org/x/perf/cmd/benchstat</code>
您可以使用它比较两组基准结果:
<code class="bash">benchstat old.txt new.txt</code>
PPROF :GO的内置分析工具,可用于分析CPU和内存使用情况。您可以在基准中启用CPU分析:
<code class="go">func BenchmarkMyFunction(b *testing.B) { b.Run("CPU", func(b *testing.B) { b.SetParallelism(1) b.ReportAllocs() b.ResetTimer() for i := 0; i </code>
然后在启用分析的情况下运行基准:
<code class="bash">go test -bench=BenchmarkMyFunction -cpuprofile cpu.out</code>
然后,您可以通过以下方式分析个人资料
go tool pprof cpu.out
基准图:一种随着时间的推移可视化基准结果的工具。它可以安装:
<code class="bash">go get github.com/ajstarks/svgo/benchplot</code>
您可以使用它来从基准结果生成图:
<code class="bash">benchplot -t "My Benchmark" -o mybenchmark.png old.txt new.txt</code>
Go-Torch :可视化GO执行跟踪的工具。它可以安装:
<code class="bash">go get github.com/uber/go-torch</code>
您可以使用:
<code class="bash">go test -bench=BenchmarkMyFunction -trace trace.out</code>
然后将其可视化:
<code class="bash">go-torch trace.out</code>
这些工具与GO的测试软件包一起使用时,可以全面了解您的代码性能,并帮助您有效地优化它。
以上是如何使用测试包进行基准GO代码?的详细内容。更多信息请关注PHP中文网其他相关文章!