locust2.0+教程:004 - 等待时间和执行权重

wait_time:等待时间,是指用户在每个任务执行后等待多少时间,等待时间可以促使性能测试更贴近实际中的场景,单位为秒。例如wait_time = between(2, 5)表示等待2-5秒之间,选择的值是随机的,我们可以通过查看详情源码中包含:random.random()得知。

def between(min_wait, max_wait):
    """
    Returns a function that will return a random number between min_wait and max_wait.

    Example::

        class MyUser(User):
            # wait between 3.0 and 10.5 seconds after each task
            wait_time = between(3.0, 10.5)
    """
    return lambda instance: min_wait + random.random() * (max_wait - min_wait)

@task:执行权重。@task修饰的方法是locust文件的核心。通过用@task修饰方法声明任务,方法的权重更高,被选择执行的概率就越高,长期运行后,执行的比例趋向于@task装饰的比例。对于每个正在运行的用户,locust都会创建一个greenlet(微线程),用于调用这些方法。以下面的案例为例。get("/hello")的装饰权重为1,get("/world")的装饰权重为3,则,运行的时候,大致会按1:3的执行次数进行。

locust脚本源码:my_locust.py

from locust import HttpUser, task, between


class QuickstartUser(HttpUser):
    wait_time = between(2, 5)

    @task
    def hello(self):
        self.client.get("/hello")

    @task(3)
    def world(self):
        self.client.get("/world")

服务端sanic源码:main.py

from sanic import Sanic
import datetime
from sanic import response

app = Sanic('myapp')


@app.get('/hello')
def handle_request(request):
    time = str(datetime.datetime.now())[:-7]
    return response.json({"hello time": time})


@app.get('/world')
def handle_request(request):
    time = str(datetime.datetime.now())[:-7]
    return response.json({"world time": time})


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=7890, auto_reload=True)

1、命令行执行:locust -f my_locust.py
2、打开http://localhost:8089/。
3、用户数,孵化率,host分别输入1,1,http://127.0.0.1:7890
4、点击运行

服务端具体运行情况:我们就可以看到,等待时间都是在2-5秒之间。
并且hello的请求次数和world的请求次数大致为1:3。
图片

locust客户端:hello的请求次数和world的请求次数大致也是1:3。
图片

以上,即wait_time和@task的解析和案例说明。

微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值