Debian Codegraph @

benchmarks/command_packer_benchmark.py

raw
1 from base import Benchmark
2
3 from valkey.connection import SYM_CRLF, SYM_DOLLAR, SYM_EMPTY, SYM_STAR, Connection
4
5
6 class StringJoiningConnection(Connection):
7 def send_packed_command(self, command, check_health=True):
8 "Send an already packed command to the Valkey server"
9 if not self._sock:
10 self.connect()
11 try:
12 self._sock.sendall(command)
13 except OSError as e:
14 self.disconnect()
15 if len(e.args) == 1:
16 _errno, errmsg = "UNKNOWN", e.args[0]
17 else:
18 _errno, errmsg = e.args
19 raise ConnectionError(f"Error {_errno} while writing to socket. {errmsg}.")
20 except Exception:
21 self.disconnect()
22 raise
23
24 def pack_command(self, *args):
25 "Pack a series of arguments into a value Valkey command"
26 args_output = SYM_EMPTY.join(
27 [
28 SYM_EMPTY.join(
29 (SYM_DOLLAR, str(len(k)).encode(), SYM_CRLF, k, SYM_CRLF)
30 )
31 for k in map(self.encoder.encode, args)
32 ]
33 )
34 output = SYM_EMPTY.join(
35 (SYM_STAR, str(len(args)).encode(), SYM_CRLF, args_output)
36 )
37 return output
38
39
40 class ListJoiningConnection(Connection):
41 def send_packed_command(self, command, check_health=True):
42 if not self._sock:
43 self.connect()
44 try:
45 if isinstance(command, str):
46 command = [command]
47 for item in command:
48 self._sock.sendall(item)
49 except OSError as e:
50 self.disconnect()
51 if len(e.args) == 1:
52 _errno, errmsg = "UNKNOWN", e.args[0]
53 else:
54 _errno, errmsg = e.args
55 raise ConnectionError(f"Error {_errno} while writing to socket. {errmsg}.")
56 except Exception:
57 self.disconnect()
58 raise
59
60 def pack_command(self, *args):
61 output = []
62 buff = SYM_EMPTY.join((SYM_STAR, str(len(args)).encode(), SYM_CRLF))
63
64 for k in map(self.encoder.encode, args):
65 if len(buff) > 6000 or len(k) > 6000:
66 buff = SYM_EMPTY.join(
67 (buff, SYM_DOLLAR, str(len(k)).encode(), SYM_CRLF)
68 )
69 output.append(buff)
70 output.append(k)
71 buff = SYM_CRLF
72 else:
73 buff = SYM_EMPTY.join(
74 (buff, SYM_DOLLAR, str(len(k)).encode(), SYM_CRLF, k, SYM_CRLF)
75 )
76 output.append(buff)
77 return output
78
79
80 class CommandPackerBenchmark(Benchmark):
81
82 ARGUMENTS = (
83 {
84 "name": "connection_class",
85 "values": [StringJoiningConnection, ListJoiningConnection],
86 },
87 {
88 "name": "value_size",
89 "values": [10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000],
90 },
91 )
92
93 def setup(self, connection_class, value_size):
94 self.get_client(connection_class=connection_class)
95
96 def run(self, connection_class, value_size):
97 r = self.get_client()
98 x = "a" * value_size
99 r.set("benchmark", x)
100
101
102 if __name__ == "__main__":
103 CommandPackerBenchmark().run_benchmark()