Locust性能-零基礎入門系列(1)

本篇文章,從局部出發,利用一個簡單的測試,來講明場景模擬的wait_time屬性的用法。wait_time爲何要單獨拎出來說,是由於它主要有兩種模式,而初學者對這兩種模式,容易混淆。python

1)
app

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

第一種模式,能夠使用以上2種模式,他們的用法都是一致的,都是當任務完成以後,停頓3秒或者是5-15秒之間選擇一個停頓的時間做爲停頓的時間。其兩種方式的源碼以下:dom

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


第二種模式,以下:ide

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)

說明:spa

line 1: 導入相關的包。code

line 3: 定義一個用戶類MyUser,這個類要繼承Locust User類繼承

line 5: 定義一個任務方法ci

line 4: 添加@task 修飾符, 若是不添加,那麼任務方法就不會被執行。

line 7/8/9:是上面已經講過的,關於wait_time屬性的設置,有2大類方式,這裏就再也不贅述。

若是安裝以上的場景定義,那麼執行的結果就是,每隔1秒鐘就會執行1次my_task任務。


你們也能夠掃描並關注以下公衆號「TimTest」,會有更多性能測試相關內容分享。

qrcode_for_gh_39009e949117_258-1.jpg

相關文章
相關標籤/搜索