Skip to content

Instantly share code, notes, and snippets.

@Shitaibin
Last active November 28, 2018 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shitaibin/9593a18989b6c81bb3aae5ccdf9b6470 to your computer and use it in GitHub Desktop.
Save Shitaibin/9593a18989b6c81bb3aae5ccdf9b6470 to your computer and use it in GitHub Desktop.
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