8

I'm testing this Go code on my VirtualBoxed Ubuntu 11.4

package main

import ("fmt";"time";"big")
var c chan *big.Int

func sum( start,stop,step int64) {
    bigStop := big.NewInt(stop)
    bigStep := big.NewInt(step)
    bigSum  := big.NewInt(0)
    for i := big.NewInt(start);i.Cmp(bigStop)<0 ;i.Add(i,bigStep){
        bigSum.Add(bigSum,i)
    }
    c<-bigSum           
}

func main() {
    s := big.NewInt( 0 )
    n := time.Nanoseconds()

    step := int64(4)
    c = make( chan *big.Int , int(step))
    stop := int64(100000000)
    for j:=int64(0);j<step;j++{
        go sum(j,stop,step)     
    }
    for j:=int64(0);j<step;j++{
        s.Add(s,<-c)
    }
    n = time.Nanoseconds() - n
    fmt.Println(s,float64(n)/1000000000.)
}

Ubuntu has access to all my 4 cores. I checked this with simultaneous run of several executables and System Monitor. But when I'm trying to run this code, it's using only one core and is not gaining any profit of parallel processing.

What I'm doing wrong?

2 Answers 2

24

You probably need to review the Concurrency section of the Go FAQ, specifically these two questions, and work out which (if not both) apply to your case:

Why doesn't my multi-goroutine program use multiple CPUs?

You must set the GOMAXPROCS shell environment variable or use the similarly-named function of the runtime package to allow the run-time support to utilize more than one OS thread.

Programs that perform parallel computation should benefit from an increase in GOMAXPROCS. However, be aware that concurrency is not parallelism.

Why does using GOMAXPROCS > 1 sometimes make my program slower?

It depends on the nature of your program. Programs that contain several goroutines that spend a lot of time communicating on channels will experience performance degradation when using multiple OS threads. This is because of the significant context-switching penalty involved in sending data between threads.

Go's goroutine scheduler is not as good as it needs to be. In future, it should recognize such cases and optimize its use of OS threads. For now, GOMAXPROCS should be set on a per-application basis.

For more detail on this topic see the talk entitled Concurrency is not Parallelism.

Sign up to request clarification or add additional context in comments.

2 Comments

also note that the default seems to be "1"
The default with go1.6.3 on OSX 10.11 is the number of CPU cores. I believe it was changed in Go v1.5.
0

Note that as of a long time ago (Go 1.5, on 19 Aug 2015), GOMAXPROCS now defaults to the number of threads on your machine. So if you have an intel processor with 4 cores and each has hyperthreading enabled, runtime.GOMAXPROCS(0) will return 8.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.