我们执行命令go test -test.bench=".*" ,可以看到如下结果:
PASS
Benchmark_Division 500000000 7.76 ns/op
Benchmark_TimeConsumingFunction 500000000 7.80 ns/op
ok gotest 9.364s
上面的结果显示我们没有执行任何TestXXX的单元测试函数,显示的结果只执行了压力测试函数,第一条显示了Benchmark_Division执行了500000000次,每次的执行平均时间是7.76纳秒,第二条显示了Benchmark_TimeConsumingFunction执行了500000000,每次的平均执行时间是7.80纳秒。最后一条显示总共的执行时间。
我们执行命令go test -test.bench=".*" -count=5,可以看到如下结果: (使用-count可以指定执行多少次)
PASS
Benchmark_Division-2 300000000 4.60 ns/op
Benchmark_Division-2 300000000 4.57 ns/op
Benchmark_Division-2 300000000 4.63 ns/op
Benchmark_Division-2 300000000 4.60 ns/op
Benchmark_Division-2 300000000 4.63 ns/op
Benchmark_TimeConsumingFunction-2 300000000 4.64 ns/op
Benchmark_TimeConsumingFunction-2 300000000 4.61 ns/op
Benchmark_TimeConsumingFunction-2 300000000 4.60 ns/op
Benchmark_TimeConsumingFunction-2 300000000 4.59 ns/op
Benchmark_TimeConsumingFunction-2 300000000 4.60 ns/op
ok _/home/diego/GoWork/src/app/testing 18.546s
go test -run=文件名字 -bench=bench名字 -cpuprofile=生产的cprofile文件名称 文件夹
例子:
testBenchMark下有个popcnt文件夹,popcnt中有文件popcunt_test.go
➜ testBenchMark ls
popcnt
popcunt_test.go的问价内容:
ackage popcnt
import (
"testing"
)
const m1 = 0x5555555555555555
const m2 = 0x3333333333333333
const m4 = 0x0f0f0f0f0f0f0f0f
const h01 = 0x0101010101010101
func popcnt(x uint64) uint64 {
x -= (x >> 1) & m1
x = (x & m2) + ((x >> 2) & m2)
x = (x + (x >> 4)) & m4
return (x * h01) >> 56
}
func BenchmarkPopcnt(b *testing.B) {
for i := 0; i < b.N; i++ {
x := i
x -= (x >> 1) & m1
x = (x & m2) + ((x >> 2) & m2)
x = (x + (x >> 4)) & m4
_ = (x * h01) >> 56
}
}
然后运行go test -bench=".*" -cpuprofile=cpu.profile ./popcnt
➜ testBenchMark go test -bench=".*" -cpuprofile=cpu.profile ./popcnt
testing: warning: no tests to run
PASS
BenchmarkPopcnt-8 1000000000 2.01 ns/op
ok app/testBenchMark/popcnt 2.219s
➜ testBenchMark ll
total 6704
drwxr-xr-x 5 diego staff 170 5 6 13:57 .
drwxr-xr-x 3 diego staff 102 5 6 11:12 ..
-rw-r--r-- 1 diego staff 5200 5 6 13:57 cpu.profile
drwxr-xr-x 4 diego staff 136 5 6 11:47 popcnt
-rwxr-xr-x 1 diego staff 3424176 5 6 13:57 popcnt.test
➜ testBenchMark
生产 cpu.profile问价和popcnt.test 文件
➜ testBenchMark ll
total 6704
drwxr-xr-x 5 diego staff 170 5 6 13:57 .
drwxr-xr-x 3 diego staff 102 5 6 11:12 ..
-rw-r--r-- 1 diego staff 5200 5 6 13:57 cpu.profile
drwxr-xr-x 3 diego staff 102 5 6 14:01 popcnt
-rwxr-xr-x 1 diego staff 3424176 5 6 13:57 popcnt.test
➜ testBenchMark









