I am learning and trying the WaitGroup functionality in Golang. Here is my code:
package main
import (
"atomic"
"http"
"log"
"sync"
"time"
)
func makeRequest(n int) {
wg := sync.WaitGroup{}
count := atomic.Int32{}
wg.Add(n)
s := time.Now()
for j := 0; j < n; j++ {
go myGoRoutine(&wg, &count)
}
wg.Wait()
log.Printf("Time Elapsed: %v for %d iterations", time.Since(s), n)
}
func myGoRoutine(wg *sync.WaitGroup, count *atomic.Int32) {
defer wg.Done()
_, err := http.Get("https://jsonplaceholder.typicode.com/todos/1")
if err != nil {
log.Printf("Error: %v", err.Error())
}
count.Add(1)
}
func main() {
cases := []int{1, 10, 100, 1000, 10000}
for _, c := range cases {
makeRequest(c)
}
}
This is the output:
2023/12/28 07:31:34 Time Elapsed: 936.169917ms for 1 iterations
2023/12/28 07:31:34 Time Elapsed: 16.452041ms for 10 iterations
2023/12/28 07:31:34 Time Elapsed: 37.336667ms for 100 iterations
2023/12/28 07:31:36 Time Elapsed: 2.037294792s for 1000 iterations
2023/12/28 07:32:23 Time Elapsed: 47.1717935s for 10000 iterations
Since all API calls are happening concurrently, I expect all 5 cases to take similar if not the same amount of time. This is indeed true for the first 3 cases but then it takes 2s for 1000 and over 45s for 10000 API calls.
My understanding of WaitGroup in Golang is barely a couple of days old. Its likely that I am making a mistake in the code or my fundamental understanding is incorrect. Either way, I would appreciate any help.
Summary
In detail
Go routine test with low load task
Go routine test with high load task
time.Sleep(time.Millisecond * 10).What overhead are in Goroutine and how can we handle it?
The rest of the codes