Golang基准测试的正确输出方法
Golang基准测试的正确输出方法 当我使用以下命令对此仓库(仅作为任意Go项目的占位符)运行基准测试时:
go test -run="^$" -bench="^BenchmarkLessorRevoke1000$" ./...
我得到的输出是这个,其中显示了基准测试结果:
BenchmarkLessorRevoke1000-8 1033351 1141 ns/op
但同时还有一大堆其他的测试输出。我如何让它只显示基准测试结果,而不显示测试输出呢?
更多关于Golang基准测试的正确输出方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于Golang基准测试的正确输出方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
使用 -benchtime 参数配合 -count 可以过滤掉其他输出,同时添加 -v 参数控制详细输出:
go test -bench="^BenchmarkLessorRevoke1000$" -benchtime=1x -count=1 ./...
或者使用更精确的过滤方式,通过管道配合 grep:
go test -bench="^BenchmarkLessorRevoke1000$" ./... 2>&1 | grep -E "^(Benchmark|PASS|FAIL|ok)"
如果只需要基准测试结果,可以这样:
go test -bench="^BenchmarkLessorRevoke1000$" ./... 2>&1 | grep "^Benchmark"
对于 etcd 项目,由于测试较多,建议指定具体包路径:
go test -bench="^BenchmarkLessorRevoke1000$" ./client/v3/leasing -benchtime=1x
使用 testing.B.ReportMetric 在基准测试中自定义输出格式:
func BenchmarkExample(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
// 被测代码
}
b.ReportMetric(float64(operations)/float64(b.N), "ops/ns")
}
运行基准测试时使用 -benchmem 只显示内存分配信息:
go test -bench="^BenchmarkLessorRevoke1000$" -benchmem ./...

