douzhuang2016 2013-12-01 14:09
浏览 31
已采纳

Go:缓冲通道总和更快?

Go : buffered channel sum is faster?

On the following playground link,

http://play.golang.org/p/8OAbtn6koN

One method contains buffered channel, and I expected this to perform better because it does not wait for synchronization.

 ch := make(chan int, 2)

Three methods that sums an array of random numbers. I benchmark these three functions like the following link:

http://play.golang.org/p/JK3yL4QwOJ

My expection was Buffered channel is Asynchronous and sending or receiving need not wait unless the channel is full, so the buffured channel sum performs better than unbuffered channel sum because it does not take any time to synchronize all goroutines.

[Question 1] So I gave 3 buffer size for buffered channel sum function but the benchmark result is like the following:

Benchmarklinear       10   122170091 ns/op
BenchmarkchSum        20   121921287 ns/op
testing: BenchmarkchSum left GOMAXPROCS set to 4
BenchmarkchSumBuffer        20   118524619 ns/op
testing: BenchmarkchSumBuffer left GOMAXPROCS set to 4
ok    ~/Benchmark_sum_01  4.056s

It does not make sense, why in this case the two channel sum perform the same? Should the one with buffer perform better?

[Question 2]

If I give

 ch := make(chan int, 1)

I get

Benchmarklinear       10   122170091 ns/op
BenchmarkchSum        20   121921287 ns/op
testing: BenchmarkchSum left GOMAXPROCS set to 4
BenchmarkchSumBuffer        10   118524619 ns/op
testing: BenchmarkchSumBuffer left GOMAXPROCS set to 4

If I give

 ch := make(chan int, 2)

I get

Benchmarklinear       10   122170091 ns/op
BenchmarkchSum        10   121921287 ns/op
testing: BenchmarkchSum left GOMAXPROCS set to 4
BenchmarkchSumBuffer        20   118524619 ns/op
testing: BenchmarkchSumBuffer left GOMAXPROCS set to 4

But the result is very inconsistent. Everytime I run the benchmark test, I get a different result.

buffer size does not relate to the performance? Why the benchmark with buffersize 2 gives me different results. With more buffer size, two goroutines never blocks so it seems to take less time.

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • duannong1801 2013-12-01 14:38
    关注

    The lack of buffering is inconsequential. There is a pending receive on the unbuffered channel. Therefore, as soon as you send a value on the channel it is received, which frees the channel for the next send.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示