1. 程式人生 > >自己上手寫效能測試工具(二)

自己上手寫效能測試工具(二)

上週教大家如何通過Python實現效能測試工具,最後留了一下問題,今天我們繼續來實現命令列工具。 ## 依賴庫 ``` requests==2.22.0 gevent==20.9.0 numpy==1.19.2 click==7.1.2 ``` ## click 庫 今天的主角是click庫。 中文文件:https://www.osgeo.cn/click/index.html 第一個例子(hello.py): ``` import click @click.command() @click.argument('name') @click.option('-c', default=1, help='number of greetings') def hello(name, c): for x in range(c): click.echo('Hello %s!' % name) if __name__ == "__main__": hello() ``` 檢視幫助: ``` > python3 hello.py --help Usage: hello.py [OPTIONS] NAME Options: -c INTEGER number of greetings --help Show this message and exit. ``` 使用: ```py > python3 hello.py 蟲師 -c 3 Hello 蟲師! Hello 蟲師! Hello 蟲師! ``` 現在已經掌握了click 的基本用法。 ## 實現命令列效能測試工具 接下來,將click引入到kb.py效能測試指令碼中。 ```py from __future__ import print_function import gevent from gevent import monkey monkey.patch_all() import time import click import requests from numpy import mean class statistical: pass_number = 0 fail_number = 0 run_time_list = [] def running(url, numbers): for _ in range(numbers): start_time = time.time() r = requests.get(url) if r.status_code == 200: statistical.pass_number = statistical.pass_number + 1 print(".", end="") else: statistical.fail_number = statistical.fail_number + 1 print("F", end="") end_time = time.time() run_time = round(end_time - start_time, 4) statistical.run_time_list.append(run_time) @click.command() @click.argument('url') @click.option('-u', default=1, help='執行使用者的數量,預設 1', type=int) @click.option('-q', default=1, help='單個使用者請求數,預設 1', type=int) def main(url, u, q): print("請求URL: {url}".format(url=url)) print("使用者數:{},迴圈次數: {}".format(u, q)) print("============== Running ===================") jobs = [gevent.spawn(running, url, q) for _url in range(u)] gevent.wait(jobs) print("\n============== Results ===================") print("最大: {} s".format(str(max(statistical.run_time_list)))) print("最小: {} s".format(str(min(statistical.run_time_list)))) print("平均: {} s".format(str(round(mean(statistical.run_time_list), 4)))) print("請求成功", statistical.pass_number) print("請求失敗", statistical.fail_number) print("============== end ===================") if __name__ == "__main__": main() ``` 檢視幫助: ``` python3 kb.py --help Usage: kb.py [OPTIONS] URL Options: -u INTEGER 執行使用者的數量,預設 1 -q INTEGER 單個使用者請求數,預設 1 --help Show this message and exit. ``` 使用方法: ``` > python3 kb.py https://wwww.baidu.com -u 10 -q 10 請求URL: https://wwww.baidu.com 使用者數:10,迴圈次數: 10 ============== Running =================== .................................................................................................... ============== Results =================== 最大: 0.955 s 最小: 0.2573 s 平均: 0.4585 s 請求成功 100 請求失敗 0 ============== end =================== ``` 專案程式碼:https://github.com/Sel