Skip to content

Commit 8a3b2ed

Browse files
committed
bench: add micro-benchmark for was_applied fast path
Benchmark shows ~1.1x speedup for known-LWT fast path vs regex batch detection slow path.
1 parent 7224945 commit 8a3b2ed

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

benchmarks/bench_was_applied.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
Micro-benchmark: was_applied fast path for known LWT statements.
3+
4+
Measures the speedup from skipping regex batch detection when the
5+
query already knows it's an LWT statement (is_lwt() returns True).
6+
7+
Run:
8+
python benchmarks/bench_was_applied.py
9+
"""
10+
import re
11+
import timeit
12+
from unittest.mock import Mock
13+
14+
from cassandra.query import named_tuple_factory, SimpleStatement, BatchStatement
15+
16+
17+
def bench_was_applied():
18+
"""Benchmark was_applied fast path vs slow path."""
19+
batch_regex = re.compile(r'\s*BEGIN', re.IGNORECASE)
20+
21+
# Fast path: known LWT statement (BoundStatement-like, is_lwt=True)
22+
lwt_query = Mock()
23+
lwt_query.is_lwt.return_value = True
24+
25+
def fast_path():
26+
query = lwt_query
27+
if query.is_lwt() and not isinstance(query, BatchStatement):
28+
# Fast path - known single LWT, skip batch detection
29+
pass
30+
31+
# Slow path: non-LWT SimpleStatement (must check regex)
32+
non_lwt_query = Mock(spec=SimpleStatement)
33+
non_lwt_query.is_lwt.return_value = False
34+
non_lwt_query.query_string = "INSERT INTO t (k, v) VALUES (1, 2) IF NOT EXISTS"
35+
36+
def slow_path():
37+
query = non_lwt_query
38+
if query.is_lwt() and not isinstance(query, BatchStatement):
39+
pass
40+
else:
41+
isinstance(query, BatchStatement) or \
42+
(isinstance(query, SimpleStatement) and batch_regex.match(query.query_string))
43+
44+
n = 500_000
45+
t_fast = timeit.timeit(fast_path, number=n)
46+
t_slow = timeit.timeit(slow_path, number=n)
47+
48+
print(f"Fast path (known LWT, {n} iters): {t_fast:.3f}s ({t_fast / n * 1e6:.2f} us/call)")
49+
print(f"Slow path (regex check, {n} iters): {t_slow:.3f}s ({t_slow / n * 1e6:.2f} us/call)")
50+
print(f"Speedup: {t_slow / t_fast:.1f}x")
51+
52+
53+
if __name__ == '__main__':
54+
bench_was_applied()

0 commit comments

Comments
 (0)