package main
import (
"github.com/montanaflynn/stats"
"log"
"net/http"
"time"
)
type RequestResponse struct {
TimeCost int64
Response *http.Response
}
func main() {
url := "https://www.baidu.com"
method := "GET"
responses := batchRequest(1000, url, method)
log.Println("", len(responses))
resultStats(responses)
}
func resultStats(responses []*RequestResponse) {
timeCosts := make([]float64, len(responses))
for i, resp := range responses {
timeCosts[i] = float64(resp.TimeCost)
}
percentile, _ := stats.Percentile(timeCosts, 95)
mean, _ := stats.Mean(timeCosts)
log.Printf("95-percentile: %.3f", percentile)
log.Printf("average: %.3f", mean)
}
func batchRequest(concurrency int, url string, method string) []*RequestResponse {
ch := make(chan *RequestResponse, concurrency)
index := 0
for index < concurrency {
go func(index int, url string, method string) {
resp := doRequest(url, method)
ch <- resp
log.Println(index)
}(index, url, method)
index++
}
requestResponses := make([]*RequestResponse, concurrency)
index = 0
for index < concurrency {
requestResponses[index] = <-ch
index++
}
return requestResponses
}
func doRequest(url string, method string) *RequestResponse {
startTs := time.Now()
req, _ := http.NewRequest(method, url, nil)
resp, _ := http.DefaultClient.Do(req)
timeCost := time.Now().Sub(startTs).Milliseconds()
return &RequestResponse{TimeCost: timeCost, Response: resp}
}
评论