locust快速入门--自定义用户增长形状

本文介绍了如何在Locust中定制用户增长模型,以便分析不同用户量对服务器的影响。作者提供了一个使用`CustomShape`类的代码示例,通过控制用户每增长5人,压测10秒,直到达到100人的目标用户数。
摘要由CSDN通过智能技术生成

背景:

locust 默认的用户增长模式,不方便分析不同用户量大对服务器的压力影响。因此,需要对用户增加的图形进行自定义。

locust官网说明:https://docs.locust.io/en/stable/custom-load-shape.html

自定义不同时间段用户的数量,以及执行的用例集合
指定用户及不同阶段用户数量

代码实例:

  • 核心代码用户每增长(step_load )5,持续压测(step_time )10秒,目标用户数量(target_user_count)100
from locust import LoadTestShape
class CustomShape(LoadTestShape):
    last_update_time = 0 # 上一次更新的时间
    step_time = 10 # 当前用户数量持续的时长,单位秒
    step_load = 5 # 每阶段用户的差值
    target_user_count= 100 # 最终用户的数量为

    def tick(self):
        current_user_num= self.get_current_user_count()
        SERVICE_SIGN.LOGGER.info(f'当前用户{current_user_num} 目标:{self.target_user_count} 当前运行时间 {self.get_run_time()}  上次更新时间 {self.last_update_time}')
        if current_user_num >= self.target_user_count:
            SERVICE_SIGN.LOGGER.info("结束")
            return None
        if not current_user_num :
            SERVICE_SIGN.LOGGER.info('初始化准备用户')
            return (self.target_user_count, self.step_load)

        if current_user_num and divmod(current_user_num,  self.step_load)[1] == 0 :
            if not self.last_update_time:
                self.last_update_time = self.get_run_time()
                SERVICE_SIGN.LOGGER.info('阶段开始')
                return (current_user_num, self.step_load)
            if round(self.get_run_time() - self.last_update_time) > self.step_time:
                self.last_update_time=0
                SERVICE_SIGN.LOGGER.info('阶段结束')
                return (current_user_num + self.step_load, self.step_load)
            else:
                SERVICE_SIGN.LOGGER.info('阶段继续')
                return (current_user_num, self.step_load)
        else:
            SERVICE_SIGN.LOGGER.info('准备阶段用户')
            return (self.target_user_count, self.step_load)
  • 在测试中的使用
from locust.env import Environment
def start_test():
		# UserRun :HttpUser用户类
		# CustomShape :LoadTestShape类,自定义的用户增长类
    env = Environment(user_classes=[UserRun], events=events,shape_class=CustomShape()) 

    runner = env.create_local_runner() # 本地单线程压力机

    web_ui = env.create_web_ui(host="127.0.0.1", port=8089)

    env.events.init.fire(environment=env, runner=runner, web_ui=web_ui)

    runner.greenlet.join()

    web_ui.stop()
  • 执行图片
    在这里插入图片描述

PS: locust的web UI图可能会有一定的偏差。通过CustomShape类的日志信息,可以确认,每阶段持续的压测时间都是固定的10秒。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值