Files
perf-harness-demo/python/locustfile.py
T

76 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Python worker(Locust 原生 HttpUser):4 类交易请求建模。
与 go/ 下的 boomer worker 跑**完全相同**的场景、请求体与用户池,
唯一差异是执行引擎(Python/GIL vs Go/goroutine),保证对比公平。
任务注册由 TASK_WEIGHTS 配置驱动(避免把任务硬写死在入口导致漏注册)。
"""
import os
import random
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import stats_dump # noqa: F401,E402 (注册 quitting 落盘监听)
from locust import HttpUser, between, task # noqa: E402
USER_POOL_SIZE = 1000 # 真随机用户池:避免全员压同一用户导致分布失真
TASK_WEIGHTS = { # 配置驱动,改权重不用动代码
"limit_open": 4,
"market_quantity_open": 2,
"market_amount_open": 2,
"batch_cancel": 1,
}
class TraderUser(HttpUser):
wait_time = between(0.001, 0.005) # 尽量压满,把瓶颈暴露给 worker 侧
def on_start(self):
self.user_id = random.randint(1, USER_POOL_SIZE)
self.open_orders = []
def _payload(self, with_price=True):
p = {
"user_id": self.user_id,
"contract_id": random.choice([1, 2, 3]),
"side": random.choice(["ask", "bid"]),
"margin_type": random.choice([1, 2]),
"quantity": str(random.randint(1, 50)),
}
if with_price:
p["price"] = str(round(random.uniform(28000, 32000), 2))
return p
@task(TASK_WEIGHTS["limit_open"])
def limit_open(self):
with self.client.post("/api/v1/order/limit/open",
json=self._payload(),
catch_response=True,
name="/api/v1/order/limit/open") as r:
if r.status_code == 200 and r.json().get("code") == 0:
self.open_orders.append(r.json()["data"]["order_id"])
else:
r.failure(f"biz error: {r.text[:100]}")
@task(TASK_WEIGHTS["market_quantity_open"])
def market_quantity_open(self):
self.client.post("/api/v1/order/market/quantity/open",
json=self._payload(with_price=False),
name="/api/v1/order/market/quantity/open")
@task(TASK_WEIGHTS["market_amount_open"])
def market_amount_open(self):
self.client.post("/api/v1/order/market/amount/open",
json=self._payload(with_price=False),
name="/api/v1/order/market/amount/open")
@task(TASK_WEIGHTS["batch_cancel"])
def batch_cancel(self):
ids, self.open_orders = self.open_orders[:10], self.open_orders[10:]
self.client.request("DELETE", "/api/v1/order/batch/cancel",
json={"user_id": self.user_id,
"order_ids": ids or [0]},
name="/api/v1/order/batch/cancel")