暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Locust性能-零基础入门系列(1)

TimTest 2020-09-19
283
本篇文章,从局部出发,利用一个简单的测试,来说明场景模拟的wait_time属性的用法。wait_time为什么要单独拎出来讲,是因为它主要有两种模式,而初学者对这两种模式,容易混淆。

1)
    wait_time = constant(3)
    wait_time = between(5,15

    第一种模式,可以使用以上2种模式,他们的用法都是一致的,都是当任务完成之后,停顿3秒或者是5-15秒之间选择一个停顿的时间作为停顿的时间。其两种方式的源码如下:

      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)




        def constant(wait_time):
        """
        Returns a function that just returns the number specified by the wait_time argument

        Example::

        class MyUser(User):
        wait_time = constant(3)
        """
        return lambda instance: wait_time


        第二种模式,如下:

           wait_time = constant_pacing(1)

          和第一种模式就有很大的不同了。它是计时性的,也就是每1秒钟触发执行一次任务,而不管任务有没有执行完。源码如下:

            def constant_pacing(wait_time):
            """
            Returns a function that will track the run time of the tasks, and for each time it's
            called it will return a wait time that will try to make the total time between task
            execution equal to the time specified by the wait_time argument.

            In the following example the task will always be executed once every second, no matter
            the task execution time::

            class MyUser(User):
            wait_time = constant_pacing(1)
            @task
            def my_task(self):
            time.sleep(random.random())

            If a task execution exceeds the specified wait_time, the wait will be 0 before starting
            the next task.
            """
            所以大家可以在实际的工作中根据需求来自行选择。但是前提是大家要对这些选项和用法掌握,避免不清楚而导致工作失误。


            下面是一个简单的locust file 代码讲解,算是一个很基础的一个入门。

              from locust import User, task,between,constant,constant_pacing


              class MyUser(User):
              @task
              def my_task(self):
              print("executing my_task")
              #wait_time = between(5,15)
              #wait_time = constant(3)
              wait_time = constant_pacing(1)

              说明:

              line 1: 导入相关的包。

              line 3: 定义一个用户类MyUser,这个类要继承Locust User类

              line 5: 定义一个任务方法

              line 4: 添加@task 修饰符, 如果不添加,那么任务方法就不会被执行。

              line 7/8/9:是上面已经讲过的,关于wait_time属性的设置,有2大类方式,这里就不再赘述。

              如果安装以上的场景定义,那么执行的结果就是,每隔1秒钟就会执行1次my_task任务。


              文章转载自TimTest,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

              评论