Hi,

As a fun way of getting into Go I decided to create a "random" number 
generator by timing a number of requests to a specific URL, and reducing 
the results to one number. For practice pusposes I made a  "naive" version 
with just a for loop and a version that uses goroutines.
As I am interested in the timings for each individual request, there was an 
interesting result. Implemented in the for loop, each request was timed as 
expected. For the goroutines however the timings incremented for each 
individual timing, where the last timing was equal or a microsecond or so 
below the total timing for all requests.
Upon further inspection, it seems that the time.Now() for the startTime is 
called almost immediately for all, but the time.Now() for the stopSub is 
called much later.
How is it possible that all goroutines start execution at the same time, 
but finish not at the same time? Is there maybe something blocking involved 
in http.Get()?
I posted all code for this on Stackoverflow a couple of days ago but no 
answers there yet (go - Unexpected behaviour of time.Now() in goroutine - 
Stack Overflow 
<https://stackoverflow.com/questions/71737286/unexpected-behaviour-of-time-now-in-goroutine>).
 
See below for the goroutine and how it is called.

Execution of goroutines:
*start := time.Now()*
*    ch := make(chan int64, 100)*
*    url := "https://www.nu.nl"*
*    for i := 0; i < len(timings_parallel); i++ {*
*        wg.Add(1)*
*        go func() {*
*            defer wg.Done()*
*            doGet(url, ch)*
*        }()*
*    }*
*    wg.Wait()*
*    close(ch)*
*    // feed the results from the channel into the result array*
*    count := 0*
*    for ret := range ch {*
*        timings_parallel[count] = ret*
*        count++*
*    }*
*    // get total running time for this part*
*    time_parallel := time.Since(start).Milliseconds()*
Goroutine:
*func doGet(address string, channel chan int64) {*
*    startTime := time.Now()*
*    startSub := startTime.UnixMilli()*

*    _, err := http.Get(address)*
*    if err != nil {*
*        log.Fatalln(err)*
*    }*
*    stopSub := time.Now().UnixMilli()*
*    delta := stopSub - startSub*

*    channel <- delta*
*}*


-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/9a4896fd-5e92-4462-9e6a-7363aa19a483n%40googlegroups.com.

Reply via email to