package main
import (
"flag"
"fmt"
"net/http"
"sort"
"sync"
"time"
"github.com/jiyu93/golog"
)
type FooTester struct {
TestURL string
Concurrent int
Total int
Results []int
count int
locker sync.RWMutex
}
func (f *FooTester) Run() {
wg := sync.WaitGroup{}
for i := 0; i < f.Concurrent; i++ {
wg.Add(1)
go func() {
for {
f.locker.RLock()
if f.count >= f.Total {
f.locker.RUnlock()
wg.Done()
break
}
f.locker.RUnlock()
t := f.work(f.TestURL)
f.locker.Lock()
f.Results = append(f.Results, int(t))
f.count++
f.locker.Unlock()
}
}()
}
wg.Wait()
}
func (f *FooTester) work(u string) int {
t1 := time.Now()
http.Get(u)
return int(time.Now().Sub(t1).Milliseconds())
}
func (f *FooTester) Print() {
f.locker.RLock()
defer f.locker.RUnlock()
var sum, avg int
for _, v := range f.Results {
sum += v
}
avg = sum / len(f.Results)
sort.Ints(f.Results)
pos := int(float64(len(f.Results)) * 0.95)
fmt.Println("平均响应时间: ", avg, "ms")
fmt.Println("95%响应时间: ", f.Results[pos], "ms")
}
func main() {
testURL := flag.String("u", "", "测试URL")
cc := flag.Int("c", 0, "并发")
total := flag.Int("t", 0, "总请求次数")
flag.Parse()
if len(*testURL) == 0 || *cc <= 0 || *total <= 0 {
golog.Info("参数错误")
return
}
t := FooTester{
TestURL: *testURL,
Concurrent: *cc,
Total: *total,
Results: make([]int, 0),
}
t.Run()
t.Print()
}
评论