Reputation: 35
The purpose of this code is to calculate each connected time between my computer and google.com using go routine.but the result seems wrong.why time keep increasing. what's go on here?
2013/12/04 16:10:41 www.google.com 597.175072ms
2013/12/04 16:10:41 www.google.com 608.161898ms
2013/12/04 16:10:41 www.google.com 614.527441ms
2013/12/04 16:10:41 www.google.com 620.51907ms
2013/12/04 16:10:41 www.google.com 630.052257ms
2013/12/04 16:10:42 www.google.com 654.539717ms
2013/12/04 16:10:42 www.google.com 659.144724ms
2013/12/04 16:10:42 www.google.com 1.282230659s
2013/12/04 16:10:42 www.google.com 1.353469764s
package main
import (
"log"
"net"
"net/http"
"time"
"sync"
)
var wg sync.WaitGroup
func main() {
url := "http://www.google.com"
for i := 0; i < 9; i++ {
wg.Add(1)
go request(url)
}
wg.Wait()
}
func dialTimeout(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, time.Duration(1*time.Second))
}
func request(url string) {
var t0, t1 time.Time
transport := http.Transport{
Dial: dialTimeout,
}
client := http.Client{
Transport: &transport,
}
t0 = time.Now()
_, err := client.Get(url)
t1 = time.Now()
if err != nil {
log.Println(err)
}
log.Println(url +" "+ t1.Sub(t0).String())
wg.Done()
}
Upvotes: 1
Views: 597
Reputation: 42433
Maybe this is the explanation: Your code is a clever way to sort the 10 connection times from fastest to slowest. Each goroutine prints the needed time once it is finished, so longer connections are printed later. As all start basically at the same moment you see "increasing connection times" but nothing is increasing, the slowest are just slow and print at the end.
http://play.golang.org/p/MzgELyNh8B shows the effect.
Upvotes: 3