Debian Codegraph @

experiments/compression/client.py

raw
1 #!/usr/bin/env python
2
3 import asyncio
4 import statistics
5 import tracemalloc
6
7 from websockets.asyncio.client import connect
8 from websockets.extensions.permessage_deflate import ClientPerMessageDeflateFactory
9
10
11 CLIENTS = 20
12 INTERVAL = 1 / 10 # seconds
13
14 WB, ML = 12, 5
15
16 MEM_SIZE = []
17
18
19 async def client(num):
20 # Space out connections to make them sequential.
21 await asyncio.sleep(num * INTERVAL)
22
23 tracemalloc.start()
24
25 async with connect(
26 "ws://localhost:8765",
27 extensions=[
28 ClientPerMessageDeflateFactory(
29 server_max_window_bits=WB,
30 client_max_window_bits=WB,
31 compress_settings={"memLevel": ML},
32 )
33 ],
34 ) as ws:
35 await ws.send("hello")
36 await ws.recv()
37
38 await ws.send(b"hello")
39 await ws.recv()
40
41 MEM_SIZE.append(tracemalloc.get_traced_memory()[0])
42 tracemalloc.stop()
43
44 # Hold connection open until the end of the test.
45 await asyncio.sleep((CLIENTS + 1 - num) * INTERVAL)
46
47
48 async def clients():
49 # Start one more client than necessary because we will ignore
50 # non-representative results from the first connection.
51 await asyncio.gather(*[client(num) for num in range(CLIENTS + 1)])
52
53
54 asyncio.run(clients())
55
56
57 # First connection incurs non-representative setup costs.
58 del MEM_SIZE[0]
59
60 print(f"µ = {statistics.mean(MEM_SIZE) / 1024:.1f} KiB")
61 print(f"σ = {statistics.stdev(MEM_SIZE) / 1024:.1f} KiB")