在Ubuntu上進行Golang性能測試可以通過以下步驟進行:
創建一個以 _test.go
結尾的測試文件,例如 example_test.go
。在文件中,使用 Benchmark
開頭定義基準測試函數,函數名后可添加標識符區分不同的測試用例。例如:
package main
import "testing"
func BenchmarkAddition(b *testing.B) {
for i := 0; i < b.N; i++ {
add(1, 2)
}
}
func add(a, b int) int {
return a + b
}
使用 go test
命令運行基準測試。例如,要運行當前目錄下的所有基準測試,可以使用以下命令:
go test -bench .
可以通過參數調整測試行為,例如指定CPU核心數和測試時間:
go test -bench . -cpu=4 -benchtime=5s
測試結果通常包含以下指標:納秒每操作(ns/op)、每操作分配的字節數(B/op)和內存分配次數(allocs/op)。這些指標有助于評估代碼性能和內存使用情況。
go test -bench=. -cpuprofile=cpu.prof
go tool pprof cpu.prof
go test -bench=. -memprofile=mem.prof
go tool pprof -alloc_space mem.prof
go test -bench=. -blockprofile=block.prof
go tool pprof -http=:8080 cpu.prof
perf record -g ./your_go_program
perf report
stress -c 8 -i 4 -m 2 -t 30s
func BenchmarkParallel(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
// 并發測試代碼
}
})
}
func BenchmarkOld(b *testing.B) { /* 舊實現 */ }
func BenchmarkNew(b *testing.B) { /* 新實現 */ }
go build -gcflags="-m -m" # 查看逃逸分析
使用 benchstat
比較不同版本的性能:
go test -bench=. -count=5 > old.txt
# 修改代碼后
go test -bench=. -count=5 > new.txt
benchstat old.txt new.txt
使用 hey
進行HTTP負載測試:
hey -n 100000 -c 100 http://localhost:8080
測試時同時監控系統資源:
top -d 1 -p $(pgrep your_go_program)
watch -n 1 "ps -o rss,comm -p $(pgrep your_go_program)"
vmstat 1
在Docker中測試時注意:
docker run --cpus=4 ...
docker stats
在進行性能測試時,還應注意以下幾點: