我們上一次講到的是單元測試的有關內容,今天呢,我們再來講一下基準測試benchmarking的相關內容。
基準測試是一種測量和評估軟件性能指標的活動。
在_test.go為結尾的測試文件中,基準測試函數(shù)的格式如下:
func BenchmarkXxx(*testing.B)
通過go test命令,再加上-bench選項來執(zhí)行,多個基準測試按照順序來執(zhí)行。
函數(shù)樣例如下:
func BenchmarkHello(b *testing.B) {
for i := 0; i < b.N; i++ {
fmt.Sprintf("hello")
}
}
基準測試函數(shù)會運行目標代碼b.N次,在基準執(zhí)行期間,會不斷調整b.N直到基準測試函數(shù)持續(xù)足夠長的時間。
在運行基準測試時,也要使用go test命令,不過要在前面加上-bench=的標記,它接受一個表達式作為參數(shù),匹配基準測試的函數(shù),.表示運行所有基準測試。
除此之外,因為默認情況go test會執(zhí)行單元測試,為了防止單元測試的影響對基準測試的輸出,我們選擇使用-run=匹配一個不存在的單元測試方法即可,一般,我們不會使用none來作為單元測試的名稱,因此,我們可以使用-run=none,因此,在執(zhí)行基準測試時的命令如下:
go test -bench=. -run=none
在執(zhí)行benchmarking的時間默認為1s,但如果我們想要讓測試運行的時間更長一些,我們可以使用-benchtime來進行指定,如果是3s的話,我們就可以寫成:
go test -bench=. -benchtime=3s -run=none
如果我們在運行前基準測試需要一些耗時的配置,那么我們可以先重置定時器:
func BenchmarkBigLen(b *testing.B) {
...... // 初始化代碼
b.ResetTimer()
...... // 通常是一個for循環(huán)
}
如果基準測試要在并行設置中測試性能,那么我們可以使用RunParallel輔助函數(shù):
func BenchmarkTemplateParallel(b *testing.B) {
templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
b.RunParallel(func (pb *testing.PB) {
// every goroutine has a bytes.Buffer
var buf bytes.Buffer
for pb.Next() {
// all the goroutine run b.N times
buf.Reset()
templ.Execute(&buf, "World")
}
})
}
性能對比
前面的這個例子是一個int類型轉換為string類型的例子,但標準庫里面其實還有幾種方法,我們來看一下:
package testing2
import (
"fmt"
"strconv"
"testing"
)
func BenchmarkSprintf(b *testing.B) {
num := 10
b.ResetTimer()
for i := 0; i < b.N; i++ {
fmt.Sprintf("%d", num)
}
}
func BenchmarkFormat(b *testing.B) {
num := int64(10)
b.ResetTimer()
for i := 0; i < b.N; i++ {
strconv.FormatInt(num, 10)
}
}
func BenchmarkItoa(b *testing.B) {
num := 10
b.ResetTimer()
for i := 0; i < b.N; i++ {
strconv.Itoa(num)
}
}
/** The result is:
go test -bench=. -run=none
goos: linux
goarch: amd64
BenchmarkSprintf-4 20000000 90.8 ns/op
BenchmarkFormat-4 500000000 3.34 ns/op
BenchmarkItoa-4 300000000 5.33 ns/op
PASS
ok _/home/hdc/goProgramming/testing2 6.064s
*/
我們可以通過結果很直觀的看出來誰比較快,誰的性能更好一些。
為了進一步分析三個函數(shù)快慢的根源,可以通過-benchmem來分析內存的使用情況。-benchmem可以提供每次操作分配內存的次數(shù),以及每次操作分配的字節(jié)數(shù)。
$ go test -bench=. -benchmem -run=none
goos: linux
goarch: amd64
BenchmarkSprintf-4 20000000 91.9 ns/op 16 B/op 2 allocs/op
BenchmarkFormat-4 500000000 3.37 ns/op 0 B/op 0 allocs/op
BenchmarkItoa-4 300000000 5.30 ns/op 0 B/op 0 allocs/op
PASS
ok _/home/hdc/goProgramming/testing2 6.084s
我們發(fā)現(xiàn)結果中多出了兩個參數(shù),一個參數(shù)的單位是B/op,表示的是每次操作分配的B數(shù),另一個參數(shù)的單位是allocs/op,表示的是每次操作從堆上分配內存的次數(shù)。
pprof
除了前面所說的幾個可以用來查看的參數(shù)選項,還可以在對程序運行進行分析的時候使用下面幾個選項參數(shù):
-bench regexp:regexp可以是任何正則表達式,表示需要運行的基準測試函數(shù),一般可以使用-bench.來執(zhí)行當前目錄下所有的基準測試;
-benchmem:在輸出內容中包含基準測試的內存分配統(tǒng)計信息;
-benchtime t:t表示執(zhí)行單個測試函數(shù)的累計耗時上限,默認是1s;
-cpuprofile out:輸出cpu profile到指定的路徑,可以使用pprof來查看;
-memprofile out:輸出內存profile到指定路徑,可以使用pprof來查看
我們在執(zhí)行基準測試時,可以指定相關的選項,比如像下面這樣:
go test -bench . --benchmem -cpuprofile cpu.prof
執(zhí)行后查看目錄,多了一個cpu.prof的和一個testing2.test的文件,但這個文件是無法直接查看的,需要使用工具去解析,這是我們就可以使用pprof了。
這是一個Go語言提供的性能分析工具,可以分析cpu profile、memory profile、heap forfile、block profile等信息。
go tool pprof testing2.test cpu.prof
執(zhí)行上述命令即可。
$ go tool pprof testing2.test cpu.prof
File: testing2.test
Type: cpu
Time: May 16, 2019 at 1:46pm (CST)
Duration: 6.11s, Total samples = 6.04s (98.93%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top10
Showing nodes accounting for 5110ms, 84.60% of 6040ms total
Dropped 31 nodes (cum <= 30.20ms)
Showing top 10 nodes out of 27
flat flat% sum% cum cum%
2480ms 41.06% 41.06% 2480ms 41.06% strconv.FormatInt
750ms 12.42% 53.48% 1820ms 30.13% strconv.Itoa
590ms 9.77% 63.25% 2000ms 33.11% _/home/hdc/goProgramming/testing2.BenchmarkFormat
340ms 5.63% 68.87% 400ms 6.62% runtime.mallocgc
240ms 3.97% 72.85% 2060ms 34.11% _/home/hdc/goProgramming/testing2.BenchmarkItoa
190ms 3.15% 75.99% 450ms 7.45% fmt.newPrinter
140ms 2.32% 78.31% 300ms 4.97% fmt.(*fmt).fmt_integer
130ms 2.15% 80.46% 540ms 8.94% fmt.(*pp).doPrintf
130ms 2.15% 82.62% 260ms 4.30% sync.(*Pool).Get
120ms 1.99% 84.60% 220ms 3.64% sync.(*Pool).Put
(pprof)
此時我們就可以查看測試過程中最耗CPU的資源了。
我們來詳細的看一下每一列的含義:
第一列表示的是取樣點落在該函數(shù)里的總數(shù),比如
2480ms就代表的是248次(因為每一次固定時間為10ms);
第二列表示的是落在該函數(shù)里取樣點占總取樣點的百分比;
第三列表示的是前幾行加起來的執(zhí)行時間占總共執(zhí)行時間的多少;
第四列表示取樣點落在該函數(shù)里和它直接調用、間接調用的函數(shù)里的總數(shù);
第五列表示的是第四列的時間占總時間的百分比。
我們在查看耗費CPU資源時可以使用命令行來控制,也可以通過使用可視化圖形界面進行查看(安裝Graphviz),更進一步,我們還可以通過list命令查看具體哪一步在耗時。
(pprof) list BenchmarkItoa
Total: 6.04s
ROUTINE ======================== _/home/hdc/goProgramming/testing2.BenchmarkItoa in /home/hdc/goProgramming/testing2/request_test.go
240ms 2.06s (flat, cum) 34.11% of Total
. . 23:}
. . 24:
. . 25:func BenchmarkItoa(b *testing.B) {
. . 26: num := 10
. . 27: b.ResetTimer()
100ms 100ms 28: for i := 0; i < b.N; i++ {
140ms 1.96s 29: strconv.Itoa(num)
. . 30: }
. . 31:}
. . 32:/** The result is:
. . 33:go test -bench=. -run=none
. . 34:goos: linux
(pprof)
其中第一列表示該行的執(zhí)行時間,第二列表示該行的總執(zhí)行時間。
這樣,我們就可以知道函數(shù)的整體執(zhí)行情況了。