package main
import (
"flag"
"fmt"
"io/ioutil"
"math"
"net/http"
"sort"
"sync"
"time"
)
func main() {
var n ,c int64
var url string
flag.Int64Var(&n, "n", 0, "请求总数")
flag.Int64Var(&c,"c", 0, "请求并发数")
flag.StringVar(&url, "url", "", "请求地址")
flag.Parse()
mod := int64(math.Mod(float64(n), float64(c)))
num := int64(math.Floor(float64(n/c)))
wg := &sync.WaitGroup{}
wg.Add(int(c))
var m sync.Mutex
statData := []int64{}
totalTime := int64(0)
for i:=int64(0); i< c;i++{
requestNum := num
if i < mod {
requestNum += 1
}
go run(requestNum, url, wg, func(t int64) {
m.Lock()
defer m.Unlock()
totalTime += t
statData = append(statData, t)
})
}
wg.Wait()
sort.Slice(statData, func(i, j int) bool { return statData[i] < statData[j] })
index := int64(math.Max(math.Round(0.95 * float64(n)) - 1, 0))
fmt.Printf("[总请求数:%d、 并发数:%d ]测试结果:平均响应时间:%s、 95%s响应时间:%s \n", n, c, time.Duration(totalTime/n).String(), "%",time.Duration(statData[index]).String())
}
func run(num int64, url string, wg *sync.WaitGroup, callback func(t int64)) {
for i:=int64(0); i < num; i++ {
startTime := time.Now()
curl(url)
elapsedTime := time.Since(startTime)
callback(elapsedTime.Nanoseconds())
}
wg.Done()
}
func curl(url string) ([]byte, int) {
resp,_ := http.Get(url)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
return body, resp.StatusCode
}
评论