溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python輕量級性能工具Locust怎么安裝和使用

發(fā)布時間:2023-05-04 09:15:35 來源:億速云 閱讀:101 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要講解了“python輕量級性能工具Locust怎么安裝和使用”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“python輕量級性能工具Locust怎么安裝和使用”吧!

Locust基于python的協(xié)程機制,打破了線程進程的限制,可以能夠在一臺測試機上跑高并發(fā)

性能測試基礎(chǔ)

  1.快慢:衡量系統(tǒng)的處理效率:響應時間

  2.多少:衡量系統(tǒng)的處理能力:單位時間內(nèi)能處理多少個事務(wù)(tps)

性能測試根據(jù)測試需求最常見的分為下面三類

  1 負載測試load testing

    不斷向服務(wù)器加壓,值得預定的指標或者部分系統(tǒng)資源達到瓶頸,目的是找到系統(tǒng)最大負載的能力

  2 壓力測試

    通過高負載持續(xù)長時間,來驗證系統(tǒng)是否穩(wěn)定

  3 并發(fā)測試:

    同時像服務(wù)器提交請求,目的發(fā)現(xiàn)系統(tǒng)是否存在事務(wù)沖突或者鎖升級的現(xiàn)象

性能負載模型

python輕量級性能工具Locust怎么安裝和使用

locust安裝

安裝存在問題,可以通過豆瓣源下載

pip install locust

locust模板

基本上多數(shù)的場景我們都可以基于這個模板read.py去做修改

from locust import HttpUser, TaskSet, task, tag, events
# 啟動locust時運行
@events.test_start.add_listener
def setup(environment, **kwargs):
    # print("task setup")
# 停止locust時運行
@events.test_stop.add_listener
def teardown(environment, **kwargs):
    print("task teardown")
class UserBehavor(TaskSet):
    #虛擬用戶啟用task運行
    def on_start(self):
        print("start")
        locusts_spawned.wait()
    #虛擬用戶結(jié)束task運行
    def on_stop(self):
        print("stop")
    @tag('test1')
    @task(2)
    def index(self):
        self.client.get('/yetangjian/p/17320268.html')
    @task(1)
    def info(self):
        self.client.get("/yetangjian/p/17253215.html")
class WebsiteUser(HttpUser):
    def setup(self):
        print("locust setup")
    def teardown(self):
        print("locust teardown")
    host = "https://www.cnblogs.com"
    task_set = task(UserBehavor)
    min_wait = 3000
    max_wait = 5000

注:這里我們給了一個webhost,這樣我們可以直接在瀏覽器中打開locust

 集合點lr_rendezvous

當然我們可以把集合點操作放入上述模板的setup中去運行起來

locusts_spawned = Semaphore()
locusts_spawned.acquire()
def on_hatch_complete(**kwargs):
    """
    select_task類的鉤子函數(shù)
    :param kwargs:
    :return:
    """
    locusts_spawned.release()
events.spawning_complete.add_listener(on_hatch_complete)
n = 0
class UserBehavor(TaskSet):
    def login(self):
        global n
        n += 1
        print(f"第{n}個用戶登陸")
    def on_start(self):
        self.login()
        locusts_spawned.wait()
    @task
    def test1(self):
        #catch_response獲取返回
        with self.client.get("/yetangjian/p/17253215.html",catch_response=True):
            print("查詢結(jié)束")
class WebsiteUser(HttpUser):
    host = "https://www.cnblogs.com"
    task_set = task(UserBehavor)
    wait_time = between(1,3)
if __name__ == '__main__':
    os.system('locust -f read.py --web-host="127.0.0.1"')

比較常見的用法

在上面兩個例子中我們已經(jīng)看到了一些,例如裝飾器events.test_start.add_listener;events.test_stop.add_listener用來在負載測試前后進行一些操作,又例如on_start、on_stop,在task執(zhí)行前后運行,又例如task,可以用來分配任務(wù)的權(quán)重

 等待時間

# wait between 3.0 and 10.5 seconds after each task
#wait_time = between(3.0, 10.5)
#固定時間等待
# wait_time = constant(3)
#確保每秒運行多少次
constant_throughput(task_runs_per_second)
#確保每多少秒運行一次
constant_pacing(wait_time)

同樣也可以在User類下發(fā)重寫wait_time來達到自定義

tag標記

@tag('test1')
@task(2)
def index(self):
    self.client.get('/yetangjian/p/17320268.html')

通過對任務(wù)打標記,就可以在運行時候執(zhí)行運行某一些任務(wù):

#只執(zhí)行標記test1
os.system('locust -f read.py --tags test1 --web-host="127.0.0.1"')
#不執(zhí)行標記過的
os.system('locust -f read.py --exclude-tags --web-host="127.0.0.1"')
#除去test1執(zhí)行所有
os.system('locust -f read.py --exclude-tags test1 --web-host="127.0.0.1"')

 自定義失敗

#定義響應時間超過0.1就為失敗
with self.client.get("/yetangjian/p/17253215.html", catch_response=True) as response:
    if response.elapsed.total_seconds() > 0.1:
        response.failure("Request took too long")
#定義響應碼是200就為失敗
with self.client.get("/yetangjian/p/17320268.html", catch_response=True) as response:
    if response.status_code == 200:
        response.failure("響應碼200,但我定義為失敗")

python輕量級性能工具Locust怎么安裝和使用

 自定義負載形狀

自定義一個shape.py通過繼承LoadTestShape并重寫tick

這個形狀類將以100塊為單位,20速率的增加用戶數(shù),然后在10分鐘后停止負載測試(從運行開始的第51秒開始user_count會round到100)

from locust import LoadTestShape
class MyCustomShape(LoadTestShape):
    time_limit = 600
    spawn_rate = 20
    def tick(self):
        run_time = self.get_run_time()
        if run_time < self.time_limit:
            # User count rounded to nearest hundred.
            user_count = round(run_time, -2)
            return (user_count, self.spawn_rate)
        return None

運行圖如下所示

python輕量級性能工具Locust怎么安裝和使用

通過命令行去觸發(fā)

os.system('locust -f read.py,shape.py --web-host="127.0.0.1"')

不同時間階段的例子

from locust import LoadTestShape
class StagesShapeWithCustomUsers(LoadTestShape):
    stages = [
        {"duration": 10, "users": 10, "spawn_rate": 10},
        {"duration": 30, "users": 50, "spawn_rate": 10},
        {"duration": 60, "users": 100, "spawn_rate": 10},
        {"duration": 120, "users": 100, "spawn_rate": 10}]
    def tick(self):
        run_time = self.get_run_time()
        for stage in self.stages:
            if run_time < stage["duration"]:
                tick_data = (stage["users"], stage["spawn_rate"])
                return tick_data
        return None

感謝各位的閱讀,以上就是“python輕量級性能工具Locust怎么安裝和使用”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對python輕量級性能工具Locust怎么安裝和使用這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI