Debian Codegraph @

experiments/broadcast/clients.py

raw
1 #!/usr/bin/env python
2
3 import asyncio
4 import statistics
5 import sys
6 import time
7
8 from websockets.asyncio.client import connect
9
10
11 LATENCIES = {}
12
13
14 async def log_latency(interval):
15 while True:
16 await asyncio.sleep(interval)
17 p = statistics.quantiles(LATENCIES.values(), n=100)
18 print(f"clients = {len(LATENCIES)}")
19 print(
20 f"p50 = {p[49] / 1e6:.1f}ms, "
21 f"p95 = {p[94] / 1e6:.1f}ms, "
22 f"p99 = {p[98] / 1e6:.1f}ms"
23 )
24 print()
25
26
27 async def client():
28 try:
29 async with connect(
30 "ws://localhost:8765",
31 ping_timeout=None,
32 ) as websocket:
33 async for msg in websocket:
34 client_time = time.time_ns()
35 server_time = int(msg[:19].decode())
36 LATENCIES[websocket] = client_time - server_time
37 except Exception as exc:
38 print(exc)
39
40
41 async def main(count, interval):
42 asyncio.create_task(log_latency(interval))
43 clients = []
44 for _ in range(count):
45 clients.append(asyncio.create_task(client()))
46 await asyncio.sleep(0.001) # 1ms between each connection
47 await asyncio.wait(clients)
48
49
50 if __name__ == "__main__":
51 try:
52 count = int(sys.argv[1])
53 interval = float(sys.argv[2])
54 except Exception as exc:
55 print(f"Usage: {sys.argv[0]} count interval")
56 print(" Connect <count> clients e.g. 1000")
57 print(" Report latency every <interval> seconds e.g. 1")
58 print()
59 print(exc)
60 else:
61 asyncio.run(main(count, interval))