Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
pipeline-fan-benchmark

提示性能

增加函数

func PipelineFan() {
	in := producer(10)

	// FAN-OUT
	c1 := square(in)
	c2 := square(in)
	c3 := square(in)

	// consumer
	for _ = range merge(c1, c2, c3) {
	}
}

func PipelineSimple() {
	in := producer(10)
	ch := square(in)

	// consumer
	for _ = range ch {
	}
}

Benchmark测试函数

func BenchmarkPipelineFan(b *testing.B) {
	for i := 0; i < b.N; i++ {
		PipelineFan()
	}
}

func BenchmarkPipelineSimple(b *testing.B) {
	for i := 0; i < b.N; i++ {
		PipelineSimple()
	}
}

结果:

➜  awesome git:(master) ✗ go test -test.bench=".*"
goos: darwin
goarch: amd64
BenchmarkPipelineFan-8                 1        4012518986 ns/op
BenchmarkPipelineSimple-8              1        10028951772 ns/op
PASS
ok      _/Users/shitaibin/Code/GoWork/awesome   14.049s
➜  awesome git:(master) ✗ go test -test.bench="BenchmarkPipelineSimple"
goos: darwin
goarch: amd64
BenchmarkPipelineSimple-8              1        10031802188 ns/op
PASS
ok      _/Users/shitaibin/Code/GoWork/awesome   10.038s

不一定提升性能

func PipelineFan() {
	in := producer(5000000)

	// FAN-OUT
	c1 := square(in)
	c2 := square(in)
	c3 := square(in)

	// consumer
	for _ = range merge(c1, c2, c3) {
	}
}

func PipelineSimple() {
	in := producer(5000000)
	ch := square(in)

	// consumer
	for _ = range ch {
	}
}

结果:fan模式更耗时

➜  awesome git:(master) ✗ go test -test.bench="BenchmarkPipelineSimple"                                                                                         
goos: darwin
goarch: amd64
BenchmarkPipelineSimple-8              1        4679847821 ns/op
PASS
ok      _/Users/shitaibin/Code/GoWork/awesome   4.687s
➜  awesome git:(master) ✗ 
➜  awesome git:(master) ✗ go test -test.bench="BenchmarkPipelineFan"                                                                                        
goos: darwin
goarch: amd64
BenchmarkPipelineFan-8                 1        5260877100 ns/op
PASS
ok      _/Users/shitaibin/Code/GoWork/awesome   5.267s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.