I am experimenting with goroutine for parallelizing some computation. However, the execution time of goroutine confuse me. My experiment setup is simple.
runtime.GOMAXPROCS(3)
datalen := 1000000000
data21 := make([]float64, datalen)
data22 := make([]float64, datalen)
data23 := make([]float64, datalen)
t := time.Now()
res := make(chan interface{}, dlen)
go func() {
for i := 0; i < datalen; i++ {
data22[i] = math.Sqrt(13)
}
res <- true
}()
go func() {
for i := 0; i < datalen; i++ {
data22[i] = math.Sqrt(13)
}
res <- true
}()
go func() {
for i := 0; i < datalen; i++ {
data22[i] = math.Sqrt(13)
}
res <- true
}()
for i:=0; i<3; i++ {
<-res
}
fmt.Printf("The parallel for loop took %v to run.
", time.Since(t))
Notice that I loaded the same data in 3 goroutines, the execution time for this program is
The parallel for loop took 7.436060182s to run.
However, if I let each goroutine handle different data as follows:
runtime.GOMAXPROCS(3)
datalen := 1000000000
data21 := make([]float64, datalen)
data22 := make([]float64, datalen)
data23 := make([]float64, datalen)
t := time.Now()
res := make(chan interface{}, dlen)
go func() {
for i := 0; i < datalen; i++ {
data21[i] = math.Sqrt(13)
}
res <- true
}()
go func() {
for i := 0; i < datalen; i++ {
data22[i] = math.Sqrt(13)
}
res <- true
}()
go func() {
for i := 0; i < datalen; i++ {
data23[i] = math.Sqrt(13)
}
res <- true
}()
for i:=0; i<3; i++ {
<-res
}
fmt.Printf("The parallel for loop took %v to run.
", time.Since(t))
The execution time for this is almost 3 times more than previous and is almost equal/worse then sequential execution without goroutine
The parallel for loop took 20.744438468s to run.
I guess maybe I use the goroutine in a wrong way. So what should be the correct way to use multiple goroutines to handle different pieces of data;