|
| 1 | +# Copyright DataStax, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +""" |
| 16 | +Micro-benchmark: was_applied fast path for known LWT statements. |
| 17 | +
|
| 18 | +Measures the speedup from skipping regex batch detection when the |
| 19 | +query already knows it's an LWT statement (is_lwt() returns True). |
| 20 | +
|
| 21 | +Run: |
| 22 | + python benchmarks/bench_was_applied.py |
| 23 | +""" |
| 24 | +import re |
| 25 | +import timeit |
| 26 | +from unittest.mock import Mock |
| 27 | + |
| 28 | +from cassandra.query import named_tuple_factory, SimpleStatement, BatchStatement |
| 29 | + |
| 30 | + |
| 31 | +def bench_was_applied(): |
| 32 | + """Benchmark was_applied fast path vs slow path.""" |
| 33 | + batch_regex = re.compile(r'\s*BEGIN', re.IGNORECASE) |
| 34 | + |
| 35 | + # Fast path: known LWT statement (BoundStatement-like, is_lwt=True) |
| 36 | + lwt_query = Mock() |
| 37 | + lwt_query.is_lwt.return_value = True |
| 38 | + |
| 39 | + def fast_path(): |
| 40 | + query = lwt_query |
| 41 | + if query.is_lwt() and not isinstance(query, BatchStatement): |
| 42 | + # Fast path - known single LWT, skip batch detection |
| 43 | + pass |
| 44 | + |
| 45 | + # Slow path: non-LWT SimpleStatement (must check regex) |
| 46 | + non_lwt_query = Mock(spec=SimpleStatement) |
| 47 | + non_lwt_query.is_lwt.return_value = False |
| 48 | + non_lwt_query.query_string = "INSERT INTO t (k, v) VALUES (1, 2) IF NOT EXISTS" |
| 49 | + |
| 50 | + def slow_path(): |
| 51 | + query = non_lwt_query |
| 52 | + if query.is_lwt() and not isinstance(query, BatchStatement): |
| 53 | + pass |
| 54 | + else: |
| 55 | + isinstance(query, BatchStatement) or \ |
| 56 | + (isinstance(query, SimpleStatement) and batch_regex.match(query.query_string)) |
| 57 | + |
| 58 | + n = 500_000 |
| 59 | + t_fast = timeit.timeit(fast_path, number=n) |
| 60 | + t_slow = timeit.timeit(slow_path, number=n) |
| 61 | + |
| 62 | + print(f"Fast path (known LWT, {n} iters): {t_fast:.3f}s ({t_fast / n * 1e6:.2f} us/call)") |
| 63 | + print(f"Slow path (regex check, {n} iters): {t_slow:.3f}s ({t_slow / n * 1e6:.2f} us/call)") |
| 64 | + print(f"Speedup: {t_slow / t_fast:.1f}x") |
| 65 | + |
| 66 | + |
| 67 | +def main(): |
| 68 | + bench_was_applied() |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == '__main__': |
| 72 | + main() |
0 commit comments