Go: Multi-core parallelization problem

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.