A program of 100 million * 1000 additions was implemented serially and in parallel, with the following code:
Package Mainimport ("FMT"//"Runtime"///execute parallel segment need to introduce the packet "time") const (NUM = 100000000) type Vint struct {n []int}func (v Vint) do Add (P, I, n int, u []int, C Chan int) {tempv=v.n[p]for J: = 0; J < N J + +/For ti: = i; ti < N.; ti++ {v.n[p] + = u [Ti]} v.n[p]=tempv//Reset V.n[p]}c <-1return}func (v vint) doall (ncpu int, u []int) (sum int) {c: = make (chan int, ncpu) segment : = num/ncpufor I: = 0; i < ncpu; i++ {Go V.doadd (i, I*segment, (i+1) *segment, U, c)}for I: = 0; i < ncpu; i++ {<-c}for I: = 0; i < ncpu; i++ {sum + = V.n[i]}return}func Main () {/* parallel segment 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) *///serial segment U: = Make ([]int, NUM) for I: = 0; i < NUM; i++ {U[i] = 1}ts: = time. Now (). Unixnano () for J: = 0; J < 1000; J + + {sum: = 0for I: = 0; i < NUM; i++ {sum + = U[i]}}te: = time. NoW (). Unixnano () fmt. Println ((Te-ts)) return}
the results of serial and parallel execution are as follows:
8-Core parallelization time: 105026.076ms serial time: 80704.4503MS
The result shows that the time cost of parallelization is larger than the serial, if you know the reason, I hope to reply in the comment area
Go: Multi-core parallelization problem