分別用串行和並行實現了一個NUM次加法的程序,代碼以下:網絡
package main import ( "fmt" //"runtime" //執行並行段時須要引入該包 "time" ) const ( NUM = 50//+運算次數 ) type vint struct { n []int } func (v vint) Doadd(p, i, n int, u []int, c chan int) { for ti := i; ti < n; ti++ { v.n[p] += u[ti] time.Sleep(1 * time.Second) } c <- 1 return } func (v vint) Doall(ncpu int, u []int) (sum int) { c := make(chan int, ncpu) var segment int if NUM%ncpu == 0 { segment = NUM / ncpu } else { segment = NUM / (ncpu - 1) } for i := 0; i < ncpu; i++ { start := i * segment temp := start + segment var end int if temp < NUM { end = temp } else { end = NUM } go v.Doadd(i, start, end, u, c) } for i := 0; i < ncpu; i++ { <-c } for i := 0; i < ncpu; i++ { sum += v.n[i] } return } func main() { //*並行段 /*ncpu := runtime.NumCPU() runtime.GOMAXPROCS(ncpu) u := make([]int, NUM) for i := 0; i < NUM; i++ { u[i] = 1 } v := new(vint) v.n = make([]int, ncpu) ts := time.Now().UnixNano() sum := v.Doall(ncpu, u) te := time.Now().UnixNano() fmt.Println((te - ts), sum)*/ //串行段 u := make([]int, NUM) for i := 0; i < NUM; i++ { u[i] = 1 } ts := time.Now().UnixNano() sum := 0 for i := 0; i < NUM; i++ { sum += u[i] time.Sleep(1 * time.Second) } te := time.Now().UnixNano() fmt.Println((te - ts)) return }
1億*1000次(1億次運算,重複1000次)的串行和並行執行的結果以下: 併發
8核並行化時間: 105026.076ms 串行時間: 80704.4503msspa
由結果可知,並行化的時間開銷反而比串行大。blog
--------------------------------------------15/11/02更新---------------------------------------------內存