英文:
How to use golang Benchmark RunParallel?
问题
这是我的代码
func BenchmarkParallel(b *testing.B) {
var mu sync.Mutex
var cnt int
b.ResetTimer()
b.SetParallelism(100)
fmt.Println("cnt", cnt)
b.RunParallel(func(pb *testing.PB) {
mu.Lock()
defer mu.Unlock()
cnt++
for pb.Next() {
time.Sleep(time.Nanosecond)
// time.Sleep(time.Second)
}
})
fmt.Println("cnt", cnt)
}
$ go test -bench BenchmarkParallel -benchmem -test.count=1
收到以下输出
cnt 0
cnt 800
BenchmarkParallel-8 cnt 0
cnt 800
cnt 0
cnt 800
cnt 0
cnt 800
cnt 0
cnt 800
3987668 320.3 ns/op 0 B/op 0 allocs/op
PASS
为什么 fmt.Println 执行了这么多次,但是如果将 sleep 改为 1 秒,cnt 只输出一次?
我期望只看到 fmt.Println 一次
BenchmarkParallel
cnt 0
cnt 800
BenchmarkParallel-8 1 1001106668 ns/op
PASS
英文:
this is my code
func BenchmarkParallel(b *testing.B) {
var mu sync.Mutex
var cnt int
b.ResetTimer()
b.SetParallelism(100)
fmt.Println("cnt", cnt)
b.RunParallel(func(pb *testing.PB) {
mu.Lock()
defer mu.Unlock()
cnt++
for pb.Next() {
time.Sleep(time.Nanosecond)
// time.Sleep(time.Second)
}
})
fmt.Println("cnt", cnt)
}
$ go test -bench BenchmarkParallel -benchmem -test.count=1
Received the following output below
cnt 0
cnt 800
BenchmarkParallel-8 cnt 0
cnt 800
cnt 0
cnt 800
cnt 0
cnt 800
cnt 0
cnt 800
3987668 320.3 ns/op 0 B/op 0 allocs/op
PASS
Why does fmt.Println execute so many times,
but if sleep is changed to 1 second, cnt is only output once?
I expected to see fmt.Println only once
BenchmarkParallel
cnt 0
cnt 800
BenchmarkParallel-8 1 1001106668 ns/op
PASS
答案1
得分: 2
go test -bench
默认设计为运行 1 秒,并尽可能多次运行基准测试,但不超过该时间!所以打印的次数比你期望的多,是因为 bench 实际上运行了多次函数,以获得更好的样本大小。
当你将睡眠时间更改为 1 秒时,它只有时间运行一次基准测试样本,所以只打印一次。
你可以在这个页面上了解更多关于更改此超时时间的信息。
英文:
go test -bench
is designed to run for 1 second by default, and run the benchmark as many times as it can without exceeding that time! So the reason there are more prints than you expect is that bench is actually running your function more than once to get a better sample size.
When you change the sleep time to 1 second, then it only has time to run one sample of the benchmark, so it only prints once.
You can read more about changing this timeout on this page.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论