Apache Bench,即 ab 工具,是 Apache 提供的用来对 HTTP Web 服务器进行性能测试的工具。ab 命令不仅可以对传统的 Apache Web 服务器进行性能测试,也可以对其他的 Web 服务器进行性能测试,使用起来十分方便。
安装
在笔者 MacBook 上,ab 工具已安装好。如果是 CentOS 7 操作系统,可以使用以下命令进行安装:
yum -y install httpd-tools
测试是否安装成功:
ab -V
在笔者 MacBook 下输出:
This is ApacheBench, Version 2.3 <$Revision: 1879490 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
使用
ab 命令使用起来十分简单,例如,向 http://127.0.0.1:8080/ 接口发送 1000 次请求,请求的并发为 10:
ab -n 10000 -c 10 http://127.0.0.1:8080/
其中,参数
其他参数可以参考官方文档,https://httpd.apache.org/docs/2.4/programs/ab.html,此处不再赘述。
为进行 ab 命令的测试,我们使用 Golang 实现一个 Hello world Web 服务,当请求 http://127.0.0.1:8080/ 地址时,会返回 Hello world! 。启动 Web 服务后,执行上述 ab 命令,得到输出:
This is ApacheBench, Version 2.3 <$Revision: 1879490 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking 127.0.0.1 (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests
Server Software:
Server Hostname: 127.0.0.1
Server Port: 8080
Document Path: /
Document Length: 12 bytes
Concurrency Level: 10
Time taken for tests: 0.642 seconds
Complete requests: 10000
Failed requests: 0
Total transferred: 1290000 bytes
HTML transferred: 120000 bytes
Requests per second: 15582.34 [#/sec] (mean)
Time per request: 0.642 [ms] (mean)
Time per request: 0.064 [ms] (mean, across all concurrent requests)
Transfer rate: 1963.01 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.1 0 1
Processing: 0 0 0.2 0 5
Waiting: 0 0 0.2 0 5
Total: 0 1 0.3 1 5
Percentage of the requests served within a certain time (ms)
50% 1
66% 1
75% 1
80% 1
90% 1
95% 1
98% 1
99% 1
100% 5 (longest request)
输出包含:
Complete requests :成功获取返回的请求数量Concurrency Level :测试中使用并发客户端数量,即并发数Time taken for tests :处理完成所有请求的时间Requests per second :每秒处理请求的数量,即(请求数量 / 处理时间)的值Time per request :每个请求的平均处理时间。存在两个值,第一个值:并发数 * 处理时间 * 1000 / 总请求数量;第二个值:处理时间 * 1000 / 总请求数量
例如,第一个 Time per request :
10 * 0.642 * 1000 / 10000 = 0.642 (ms)
第二个 Time per request :
0.642 * 1000 / 10000 = 0.064 (ms)
这些指标可以综合反映了服务器的性能情况,
参考资料
- https://httpd.apache.org/docs/2.4/programs/ab.html
- https://www.tutorialspoint.com/apache_bench/apache_bench_quick_guide.htm
- https://www.petefreitag.com/item/689.cfm
- https://www.skenz.it/cs/ab
- https://diamantidis.github.io/2020/07/15/load-testing-with-apache-bench
- https://zhuanlan.zhihu.com/p/102534511
- https://zhuanlan.zhihu.com/p/99789141
附:测试程序
附上 Go 实现的接口,为简单起见,去除了异常的处理:
package main
import (
"fmt"
"net/http"
)
func Hello(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "Hello world!")
}
func main() {
http.HandleFunc("/", Hello)
http.ListenAndServe(":8080", nil)
}
|