forked from scylladb/python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutf8_decode_benchmark.py
More file actions
330 lines (254 loc) · 11.8 KB
/
Copy pathutf8_decode_benchmark.py
File metadata and controls
330 lines (254 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# Copyright ScyllaDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Benchmarks for UTF-8 and ASCII deserialization in the Cython row parser.
This optimization replaces the two-step to_bytes(buf).decode('utf8') with
a direct PyUnicode_DecodeUTF8(buf.ptr, buf.size, NULL) call, eliminating
an intermediate bytes object allocation per text cell.
Requires: pip install pytest-benchmark
Run with: pytest benchmarks/utf8_decode_benchmark.py -v --benchmark-sort=name
Compare before/after by running on master vs this branch.
Correctness tests live in tests/unit/cython/test_deserializers.py.
"""
import struct
import pytest
pytest.importorskip("pytest_benchmark")
pytest.importorskip("cassandra.obj_parser")
from cassandra.obj_parser import ListParser
from cassandra.bytesio import BytesIOReader
from cassandra.parsing import ParseDesc
from cassandra.deserializers import make_deserializers
from cassandra.cqltypes import UTF8Type, AsciiType, Int32Type
from cassandra.policies import ColDesc
def _build_text_rows_buffer(num_rows, num_cols, text_data):
"""Build a binary buffer representing num_rows x num_cols of text data.
Format: [int32 row_count] [row1] [row2] ...
Each row: [cell1] [cell2] ...
Each cell: [int32 length] [data bytes]
"""
parts = [struct.pack(">i", num_rows)]
cell = struct.pack(">i", len(text_data)) + text_data
row = cell * num_cols
parts.append(row * num_rows)
return b"".join(parts)
def _build_mixed_rows_buffer(num_rows, text_data, int_value=42):
"""Build a buffer with mixed columns: 3 text + 2 int32."""
parts = [struct.pack(">i", num_rows)]
text_cell = struct.pack(">i", len(text_data)) + text_data
int_cell = struct.pack(">i", 4) + struct.pack(">i", int_value)
row = text_cell + text_cell + text_cell + int_cell + int_cell
parts.append(row * num_rows)
return b"".join(parts)
def _make_text_desc(num_cols, protocol_version=4):
"""Create a ParseDesc for num_cols text columns."""
coltypes = [UTF8Type] * num_cols
colnames = [f"col{i}" for i in range(num_cols)]
coldescs = [ColDesc("ks", "tbl", f"col{i}") for i in range(num_cols)]
desers = make_deserializers(coltypes)
return ParseDesc(colnames, coltypes, None, coldescs, desers, protocol_version)
def _make_ascii_desc(num_cols, protocol_version=4):
"""Create a ParseDesc for num_cols ASCII columns."""
coltypes = [AsciiType] * num_cols
colnames = [f"col{i}" for i in range(num_cols)]
coldescs = [ColDesc("ks", "tbl", f"col{i}") for i in range(num_cols)]
desers = make_deserializers(coltypes)
return ParseDesc(colnames, coltypes, None, coldescs, desers, protocol_version)
def _make_mixed_desc(protocol_version=4):
"""Create a ParseDesc for 3 text + 2 int32 columns."""
coltypes = [UTF8Type, UTF8Type, UTF8Type, Int32Type, Int32Type]
colnames = ["text0", "text1", "text2", "int0", "int1"]
coldescs = [ColDesc("ks", "tbl", n) for n in colnames]
desers = make_deserializers(coltypes)
return ParseDesc(colnames, coltypes, None, coldescs, desers, protocol_version)
# ---------------------------------------------------------------------------
# Cython pipeline benchmarks — UTF-8
# ---------------------------------------------------------------------------
class TestUTF8CythonPipeline:
"""Benchmark the full Cython row parsing pipeline with UTF-8 text columns.
These benchmarks measure the end-to-end cost of parsing result sets
through the optimized Cython path. The optimization replaces
to_bytes(buf).decode('utf8') with PyUnicode_DecodeUTF8(buf.ptr, buf.size, NULL),
eliminating one intermediate bytes allocation per text cell.
"""
def test_bench_utf8_1row_1col_short(self, benchmark):
"""1 row x 1 col, short string (11 bytes) — isolates per-call overhead."""
text = b"hello world"
buf = _build_text_rows_buffer(1, 1, text)
desc = _make_text_desc(1)
parser = ListParser()
def parse():
reader = BytesIOReader(buf)
return parser.parse_rows(reader, desc)
result = benchmark(parse)
assert len(result) == 1
assert result[0][0] == "hello world"
def test_bench_utf8_1row_10col_short(self, benchmark):
"""1 row x 10 cols, short strings — measures per-column overhead."""
text = b"hello world"
buf = _build_text_rows_buffer(1, 10, text)
desc = _make_text_desc(10)
parser = ListParser()
def parse():
reader = BytesIOReader(buf)
return parser.parse_rows(reader, desc)
result = benchmark(parse)
assert len(result) == 1
assert len(result[0]) == 10
def test_bench_utf8_100rows_5col_medium(self, benchmark):
"""100 rows x 5 cols, medium string (46 bytes) — typical workload."""
text = b"Hello, this is a test string for benchmarking!"
buf = _build_text_rows_buffer(100, 5, text)
desc = _make_text_desc(5)
parser = ListParser()
def parse():
reader = BytesIOReader(buf)
return parser.parse_rows(reader, desc)
result = benchmark(parse)
assert len(result) == 100
assert result[0][0] == text.decode("utf8")
def test_bench_utf8_1000rows_5col_medium(self, benchmark):
"""1000 rows x 5 cols, medium string — high-throughput scenario."""
text = b"Hello, this is a test string for benchmarking!"
buf = _build_text_rows_buffer(1000, 5, text)
desc = _make_text_desc(5)
parser = ListParser()
def parse():
reader = BytesIOReader(buf)
return parser.parse_rows(reader, desc)
result = benchmark(parse)
assert len(result) == 1000
def test_bench_utf8_100rows_5col_long(self, benchmark):
"""100 rows x 5 cols, long string (200 bytes) — larger values."""
text = b"A" * 200
buf = _build_text_rows_buffer(100, 5, text)
desc = _make_text_desc(5)
parser = ListParser()
def parse():
reader = BytesIOReader(buf)
return parser.parse_rows(reader, desc)
result = benchmark(parse)
assert len(result) == 100
assert result[0][0] == "A" * 200
def test_bench_utf8_100rows_5col_multibyte(self, benchmark):
"""100 rows x 5 cols, multibyte UTF-8 string — tests non-ASCII."""
text = "Héllo wörld! こんにちは 🌍".encode("utf-8")
buf = _build_text_rows_buffer(100, 5, text)
desc = _make_text_desc(5)
parser = ListParser()
def parse():
reader = BytesIOReader(buf)
return parser.parse_rows(reader, desc)
result = benchmark(parse)
assert len(result) == 100
assert result[0][0] == text.decode("utf-8")
# ---------------------------------------------------------------------------
# Cython pipeline benchmarks — ASCII
# ---------------------------------------------------------------------------
class TestASCIICythonPipeline:
"""Benchmark the Cython row parsing pipeline with ASCII text columns."""
def test_bench_ascii_100rows_5col_medium(self, benchmark):
"""100 rows x 5 cols, medium ASCII string."""
text = b"Hello, this is a test ASCII string for benchmarking!"
buf = _build_text_rows_buffer(100, 5, text)
desc = _make_ascii_desc(5)
parser = ListParser()
def parse():
reader = BytesIOReader(buf)
return parser.parse_rows(reader, desc)
result = benchmark(parse)
assert len(result) == 100
assert result[0][0] == text.decode("ascii")
def test_bench_ascii_1000rows_5col_medium(self, benchmark):
"""1000 rows x 5 cols, medium ASCII string."""
text = b"Hello, this is a test ASCII string for benchmarking!"
buf = _build_text_rows_buffer(1000, 5, text)
desc = _make_ascii_desc(5)
parser = ListParser()
def parse():
reader = BytesIOReader(buf)
return parser.parse_rows(reader, desc)
result = benchmark(parse)
assert len(result) == 1000
# ---------------------------------------------------------------------------
# Mixed columns benchmark
# ---------------------------------------------------------------------------
class TestMixedColumnsPipeline:
"""Benchmark with mixed column types (text + int) for realism."""
def test_bench_mixed_100rows_3text_2int(self, benchmark):
"""100 rows x (3 text + 2 int) — realistic mixed schema."""
text = b"Hello, this is a test string for benchmarking!"
buf = _build_mixed_rows_buffer(100, text)
desc = _make_mixed_desc()
parser = ListParser()
def parse():
reader = BytesIOReader(buf)
return parser.parse_rows(reader, desc)
result = benchmark(parse)
assert len(result) == 100
assert result[0][0] == text.decode("utf8")
assert result[0][3] == 42
# ---------------------------------------------------------------------------
# Python-level reference (bytes.decode) for comparison
# ---------------------------------------------------------------------------
class TestPythonDecodeReference:
"""Python-level microbenchmark showing the overhead of creating
intermediate bytes objects before decode, which is what the
original Cython code did (to_bytes(buf).decode('utf8')).
These benchmarks isolate the bytes-creation overhead that the
PyUnicode_DecodeUTF8 optimization eliminates.
"""
def test_bench_python_bytes_decode_short(self, benchmark):
"""Python reference: bytes.decode('utf8') for 500 short strings."""
data = b"hello world"
def decode_loop():
result = None
for _ in range(500):
result = data.decode("utf8")
return result
result = benchmark(decode_loop)
assert result == "hello world"
def test_bench_python_copy_then_decode_short(self, benchmark):
"""Python reference: bytes(data).decode('utf8') for 500 short strings.
This simulates the old to_bytes(buf).decode() pattern, where
to_bytes() creates a new bytes object from the C buffer."""
data = b"hello world"
mv = memoryview(data)
def decode_loop():
result = None
for _ in range(500):
copied = bytes(mv) # simulates to_bytes(buf)
result = copied.decode("utf8")
return result
result = benchmark(decode_loop)
assert result == "hello world"
def test_bench_python_bytes_decode_medium(self, benchmark):
"""Python reference: bytes.decode('utf8') for 500 medium strings."""
data = b"Hello, this is a test string for benchmarking!"
def decode_loop():
result = None
for _ in range(500):
result = data.decode("utf8")
return result
result = benchmark(decode_loop)
def test_bench_python_copy_then_decode_medium(self, benchmark):
"""Python reference: bytes(memoryview).decode('utf8') for 500 medium strings."""
data = b"Hello, this is a test string for benchmarking!"
mv = memoryview(data)
def decode_loop():
result = None
for _ in range(500):
copied = bytes(mv) # simulates to_bytes(buf)
result = copied.decode("utf8")
return result
result = benchmark(decode_loop)