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中文網其他相關文章!