package main
import ( "fmt" "net/http" "sort" "sync" "time")
type respData struct { duration float32 status int}
var wg sync.WaitGroup
func PressureTesting(url string, TotalNum, concurrentNum int) { startTime := time.Now().UnixNano() times := TotalNum/concurrentNum resChan := make(chan respData, TotalNum) for j := 0; j < times; j++ { for i := 0; i < concurrentNum; i++ { wg.Add(1) go Testing(url, resChan) } wg.Wait() fmt.Println("第",j,"次并发请求",len(resChan)) } close(resChan) testResultTime(resChan) fmt.Println("本次执行时间:",float32(time.Now().UnixNano()-startTime) / 1000000,"毫秒")}
func Testing(url string, ch chan<-respData) { var status int startTime := time.Now().UnixNano() timeout := time.Duration(time.Second) client := http.Client{ Timeout: timeout, } reqData, err := client.Get(url) duration := float32(time.Now().UnixNano()-startTime) / 1000000 if err != nil{ status = 0 } else { status = reqData.StatusCode _ = reqData.Body.Close() } ch <- respData{ duration: duration, status: status, } wg.Done()}
func testResultTime(ch chan respData) { fmt.Println("管道内元素数量", len(ch)) var sum, timeCount95 float32 var count = 0 var Count95s []float64 var wrongNum int for v := range ch { if v.status == 200 { sum += v.duration count++ Count95s = append(Count95s, float64(v.duration)) } } avg := sum / float32(count) sort.Float64s(Count95s) cutKey := int(float32(len(Count95s)) * 0.95) if Count95s != nil { timeCount95 = float32(Count95s[cutKey]) } else { timeCount95 = float32(0) } fmt.Println("平均响应时间:",avg) fmt.Println("95%响应时间:",timeCount95) fmt.Println("异常返回次数:",wrongNum)}
func main() { PressureTesting("https://www.baidu.com/", 100, 10)}
评论