在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
在进行性能测试时,还应注意以下几点: