I just want to try how fast goroutine switch context, so I wrote the code below. To my surprise, multiple gorountines run faster than the edition that does not need to switch context (I set the program to run in only one CPU core).
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
func main() {
runtime.GOMAXPROCS(1)
t_start := time.Now()
sum := 0
for j := 0; j < 10; j++ {
sum = 0
for i := 0; i < 100000000; i++ {
sum += i
}
}
fmt.Println("single goroutine takes ", time.Since(t_start))
var wg sync.WaitGroup
t_start = time.Now()
for j := 0; j < 10; j++ {
wg.Add(1)
go func() {
sum := 0
for i := 0; i < 100000000; i++ {
sum += i
}
defer wg.Done()
}()
}
wg.Wait()
fmt.Println("multiple goroutines take ", time.Since(t_start))
}
A single goroutine takes 251.690788ms, multiple goroutines take 254.067156ms
The single goroutine should run faster, because single goroutine does not need to change context. However, the answer is opposite, single mode always slower. What happened in this program?