Go的并发Chanel实现一例,现在版本的go对于cpu的利用嗅感灵敏了。
package main import "time" type Vector []int func (v Vector) DoSome(i, n int, u Vector, c chan int) { sum := 0 for ; i < n; i++ { sum += v[i] } c <- sum } const NCPU = 16 func (v Vector) DoAll(u Vector) int { c := make(chan int, NCPU) a := 0 for i := 0; i < NCPU; i++ { go v.DoSome(i * len(v) / NCPU, (i + 1) * len(v) / NCPU, u, c) } for i := 0; i < NCPU; i++ { a += <-c } return a } func Sum(a Vector) int { c := 0 for _, v := range a { c += v } return c } func main() { a := Vector{} for i := 0; i < 100000000; i++ { a = append(a, i) } start := time.Now() println(a.DoAll(a)) end := time.Now() duration := end.Sub(start) println(duration) start1 := time.Now() println(Sum(a)) end1 := time.Now() duration1 := end1.Sub(start1) println(duration1) }
输出
4999999950000000 36870300 4999999950000000 72406600
end,速度还是能看出点差别的。