Skip to content

Instantly share code, notes, and snippets.

@leizongmin
Created July 24, 2012 05:54
Show Gist options
  • Save leizongmin/3168274 to your computer and use it in GitHub Desktop.
Save leizongmin/3168274 to your computer and use it in GitHub Desktop.
http性能测试程序
package main
import (
"fmt"
"runtime"
"time"
"os"
"io/ioutil"
"net/http"
"strconv"
)
const (
DEFAULT_CLIENT = 100
DEFAULT_COUNT = 10000
NANO_TO_MILLI = 1000000
)
var oneRequest chan int
func main() {
argc := len(os.Args)
argv := os.Args
var url string
var client, count int
var err error
oneRequest = make(chan int)
var cSuccess, cError int
if argc > 1 {
url = argv[1]
if argc < 3 {
client = DEFAULT_CLIENT
count = DEFAULT_COUNT
} else {
client, err = strconv.Atoi(argv[2])
if err != nil {
client = DEFAULT_CLIENT
}
if argc >= 4 {
count, err = strconv.Atoi(argv[3])
if err != nil {
count = DEFAULT_COUNT
}
} else {
count = DEFAULT_COUNT
}
}
fmt.Printf("URL: %s Client: %d Count: %d\n", url, client, count)
argc = runtime.GOMAXPROCS(runtime.NumCPU())
for i := 0; i < client; i++ {
go doRequest(url)
}
ts := time.Now().UnixNano()
for i := 0; i < count; i++ {
x := <- oneRequest
//fmt.Println("ok.", time.Now())
if x > 0 {
cSuccess++
} else {
cError++
}
}
te := time.Now().UnixNano()
spent := te - ts
fmt.Printf("====================== Result ======================\n")
fmt.Printf("Spent %dms -- Success: %d -- Fail: %d\n", (spent / NANO_TO_MILLI), cSuccess, cError)
qps := int64(count) * NANO_TO_MILLI * 1000 / spent
qpm := int64(count) * NANO_TO_MILLI * 60000 / spent
fmt.Printf("%d req/s -- %d req/min", qps, qpm)
} else {
fmt.Println("test [url] [client] [count]")
}
}
func doRequest(url string) {
var recv int
for true {
//fmt.Println("request...", time.Now())
resp, err := http.Get(url)
if err != nil {
oneRequest <- -1
} else {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
oneRequest <- -1
} else {
oneRequest <- 1
}
recv += len(body)
}
}
return
}
@leizongmin
Copy link
Author

编译: go build test.go

使用方法: test [URL地址] [客户端数量] [总请求次数]

如: test http://127.0.0.1:8080/ 10 10000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment