Debian Codegraph @

microbenchmarks.py

raw
1 # Copyright 2009-2026 Joshua Bronson. All rights reserved.
2 #
3 # This Source Code Form is subject to the terms of the Mozilla Public
4 # License, v. 2.0. If a copy of the MPL was not distributed with this
5 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 """Microbenchmarks.
8
9 Uses https://pytest-benchmark.readthedocs.io/en/v4.0.0/pedantic.html
10 which pairs well with ../cachegrind.py (as used by ../.github/workflows/benchmark.yml).
11 """
12
13 from __future__ import annotations
14
15 import pickle
16 import typing as t
17 from collections import deque
18 from functools import partial
19
20 import pytest
21
22 import bidict
23
24
25 consume: t.Any = partial(deque, maxlen=0)
26
27 #: Rounds per benchmark. The reported figure is the min over these, so that one unlucky
28 #: sample cannot dominate a result. pedantic() defaults to a single round, i.e. no filtering.
29 ROUNDS = 5
30
31 #: Iterations per round for an operation too cheap to time on its own. Running this suite
32 #: under Cachegrind puts a fixed floor of roughly 25us on a single timed call -- three orders
33 #: of magnitude more than e.g. a lookup costs -- so unless the operation is repeated within
34 #: the round, the result is nearly all floor and carries no signal. Only valid for operations
35 #: that can be repeated without fresh setup.
36 CHEAP_ITERATIONS = 1000
37
38 #: Roughly how many items a single round should process, for operations whose cost scales
39 #: with the number of items. See :func:`scaled_iterations`.
40 TARGET_ITEMS_PER_ROUND = 20_000
41
42
43 def scaled_iterations(n: int) -> int:
44 """Iterations per round for an operation whose cost scales with *n*.
45
46 Keeps the work done per round roughly constant across sizes, so that the smallest sizes
47 clear the measurement floor described above without making the largest ones slow.
48 """
49 return max(1, TARGET_ITEMS_PER_ROUND // n)
50
51
52 #: Writes performed per timed call by the single-item write benchmarks below.
53 #:
54 #: Those benchmarks cannot use `iterations`: each needs a bidict in a known state, setup runs
55 #: once per round rather than once per iteration, and repeating a write would not exercise the
56 #: same path the second time. That left one write per timed call, which at roughly a microsecond
57 #: is far under the floor above, so the reported figure was nearly all floor. Batching this many
58 #: writes into a single timed call lifts them clear of it, at a fraction of what raising `rounds`
59 #: to the same effect would cost, since the per-round setup copies the whole bidict.
60 #:
61 #: They therefore measure the cost of a run of writes rather than of one in isolation. For the
62 #: smaller sizes the batch consumes most of the contained items, so the bidict grows or shrinks
63 #: appreciably during it -- which is representative, and identical across the revisions being
64 #: compared, so it does not affect what the comparison means.
65 WRITES_PER_ROUND = 1_000
66
67
68 def scaled_writes(n: int) -> int:
69 """How many writes the single-item write benchmarks perform per timed call, for size *n*.
70
71 Capped by *n*, since some of them consume a distinct contained item per write.
72 """
73 return min(n, WRITES_PER_ROUND)
74
75
76 LENS = (100, 1_000, 10_000)
77 DATASET_NAMES = ('int', 'str')
78
79
80 INT_DICTS_BY_LEN: dict[int, dict[int, int]] = {n: {i: i for i in range(n)} for n in LENS}
81 STR_DICTS_BY_LEN: dict[int, dict[str, str]] = {n: {f'key{i}': f'value{i}' for i in range(n)} for n in LENS}
82 DICTS_BY_KIND_AND_LEN: dict[str, dict[int, dict[t.Any, t.Any]]] = {
83 'int': INT_DICTS_BY_LEN,
84 'str': STR_DICTS_BY_LEN,
85 }
86 BIDICTS_BY_KIND_AND_LEN: dict[str, dict[int, bidict.bidict[t.Any, t.Any]]] = {
87 kind: {n: bidict.bidict(other) for n, other in dicts_by_len.items()}
88 for kind, dicts_by_len in DICTS_BY_KIND_AND_LEN.items()
89 }
90 LOOKUP_ITEMS_BY_KIND_AND_LEN: dict[str, dict[int, tuple[t.Any, t.Any]]] = {
91 kind: {n: next(iter(other.items())) for n, other in dicts_by_len.items()}
92 for kind, dicts_by_len in DICTS_BY_KIND_AND_LEN.items()
93 }
94
95 INT_BIDICTS_BY_LEN: dict[int, bidict.bidict[int, int]] = t.cast(
96 'dict[int, bidict.bidict[int, int]]',
97 BIDICTS_BY_KIND_AND_LEN['int'],
98 )
99 ORDERED_BIDICTS_BY_LEN: dict[int, bidict.OrderedBidict[int, int]] = {
100 n: bidict.OrderedBidict(INT_DICTS_BY_LEN[n]) for n in LENS
101 }
102
103 INT_DICTS_BY_LEN_DUPVAL_EARLY: dict[int, dict[int, int]] = {
104 n: dict([(0, 0), (1, 0), *((i, i) for i in range(2, n))]) for n in LENS
105 }
106 INT_DICTS_BY_LEN_DUPVAL_LATE: dict[int, dict[int, int]] = {n: {**INT_DICTS_BY_LEN[n], n - 1: 0} for n in LENS}
107
108 # One batch of items per single-item write benchmark, sized by scaled_writes(). Every item in
109 # a batch takes the same path through the code as the others, so the batch measures that path.
110
111 #: New keys and new values: no duplication.
112 SETITEM_NEW_ITEMS_BY_LEN: dict[int, list[tuple[int, int]]] = {
113 n: [(-i, -i) for i in range(1, scaled_writes(n) + 1)] for n in LENS
114 }
115 SETITEM_NEW_RESULTS_BY_LEN: dict[int, dict[int, int]] = {
116 n: INT_DICTS_BY_LEN[n] | dict(SETITEM_NEW_ITEMS_BY_LEN[n]) for n in LENS
117 }
118
119 #: Contained keys paired with new values: key duplication.
120 SETITEM_REPLACE_ITEMS_BY_LEN: dict[int, list[tuple[int, int]]] = {
121 n: [(n - i, -i) for i in range(1, scaled_writes(n) + 1)] for n in LENS
122 }
123 SETITEM_REPLACE_RESULTS_BY_LEN: dict[int, dict[int, int]] = {
124 n: INT_DICTS_BY_LEN[n] | dict(SETITEM_REPLACE_ITEMS_BY_LEN[n]) for n in LENS
125 }
126
127 #: New keys paired with contained values: value duplication, collapsing an item each time.
128 FORCEPUT_ITEMS_BY_LEN: dict[int, list[tuple[int, int]]] = {
129 n: [(-i, i - 1) for i in range(1, scaled_writes(n) + 1)] for n in LENS
130 }
131 FORCEPUT_RESULTS_BY_LEN: dict[int, dict[int, int]] = {
132 n: {k: v for k, v in INT_DICTS_BY_LEN[n].items() if k >= scaled_writes(n)} | dict(FORCEPUT_ITEMS_BY_LEN[n])
133 for n in LENS
134 }
135
136 POP_KEYS_BY_LEN: dict[int, list[int]] = {n: [n - i for i in range(1, scaled_writes(n) + 1)] for n in LENS}
137 POP_RESULTS_BY_LEN: dict[int, dict[int, int]] = {
138 n: {k: v for k, v in INT_DICTS_BY_LEN[n].items() if k not in set(POP_KEYS_BY_LEN[n])} for n in LENS
139 }
140
141 PARTIAL_OVERLAP_UPDATES_BY_LEN: dict[int, dict[int, int]] = {
142 n: {i: i for i in range(n // 2, n + (n // 2))} for n in LENS
143 }
144 PARTIAL_OVERLAP_RESULTS_BY_LEN: dict[int, dict[int, int]] = {
145 n: (INT_DICTS_BY_LEN[n] | PARTIAL_OVERLAP_UPDATES_BY_LEN[n]) for n in LENS
146 }
147
148 BIDICT_AND_DICT_LAST_TWO_ITEMS_DIFFERENT_ORDER: dict[int, tuple[bidict.bidict[int, int], dict[int, int]]] = {}
149 ORDERED_BIDICT_AND_DICT_LAST_TWO_ITEMS_DIFFERENT_ORDER: dict[
150 int, tuple[bidict.OrderedBidict[int, int], dict[int, int]]
151 ] = {}
152 for _i in LENS:
153 _bi = INT_BIDICTS_BY_LEN[_i]
154 _d = dict(_bi)
155 _last, _secondlast = _d.popitem(), _d.popitem()
156 _d[_last[0]] = _last[1] # new second-last
157 _d[_secondlast[0]] = _secondlast[1] # new last
158 BIDICT_AND_DICT_LAST_TWO_ITEMS_DIFFERENT_ORDER[_i] = (_bi, _d)
159 ORDERED_BIDICT_AND_DICT_LAST_TWO_ITEMS_DIFFERENT_ORDER[_i] = (
160 bidict.OrderedBidict(_bi),
161 _d,
162 )
163
164
165 def _setitem(bi: bidict.bidict[int, int], items: list[tuple[int, int]], _expected: dict[int, int]) -> None:
166 for key, val in items:
167 bi[key] = val
168
169
170 def _forceput(bi: bidict.bidict[int, int], items: list[tuple[int, int]], _expected: dict[int, int]) -> None:
171 for key, val in items:
172 bi.forceput(key, val)
173
174
175 def _update(bi: bidict.bidict[int, int], other: dict[int, int], _expected: dict[int, int]) -> None:
176 bi.update(other)
177
178
179 def _failing_update(bi: bidict.bidict[int, int], other: dict[int, int], _expected: dict[int, int]) -> None:
180 with pytest.raises(bidict.DuplicationError):
181 bi.update(other)
182
183
184 def _pop(bi: bidict.bidict[int, int], keys: list[int], _expected: dict[int, int]) -> None:
185 for key in keys:
186 bi.pop(key)
187
188
189 def _assert_mapping_matches(*args: t.Any) -> None:
190 assert dict(args[0]) == args[-1]
191
192
193 def _setup_setitem_new(n: int) -> tuple[tuple[t.Any, ...], dict[str, t.Any]]:
194 return ((INT_BIDICTS_BY_LEN[n].copy(), SETITEM_NEW_ITEMS_BY_LEN[n], SETITEM_NEW_RESULTS_BY_LEN[n]), {})
195
196
197 def _setup_setitem_replace_existing_key(n: int) -> tuple[tuple[t.Any, ...], dict[str, t.Any]]:
198 return ((INT_BIDICTS_BY_LEN[n].copy(), SETITEM_REPLACE_ITEMS_BY_LEN[n], SETITEM_REPLACE_RESULTS_BY_LEN[n]), {})
199
200
201 def _setup_forceput_existing_value(n: int) -> tuple[tuple[t.Any, ...], dict[str, t.Any]]:
202 return ((INT_BIDICTS_BY_LEN[n].copy(), FORCEPUT_ITEMS_BY_LEN[n], FORCEPUT_RESULTS_BY_LEN[n]), {})
203
204
205 def _setup_pop(n: int) -> tuple[tuple[t.Any, ...], dict[str, t.Any]]:
206 return ((INT_BIDICTS_BY_LEN[n].copy(), POP_KEYS_BY_LEN[n], POP_RESULTS_BY_LEN[n]), {})
207
208
209 def _setup_update_partial_overlap(n: int) -> tuple[tuple[t.Any, ...], dict[str, t.Any]]:
210 return (
211 (
212 INT_BIDICTS_BY_LEN[n].copy(),
213 PARTIAL_OVERLAP_UPDATES_BY_LEN[n],
214 PARTIAL_OVERLAP_RESULTS_BY_LEN[n],
215 ),
216 {},
217 )
218
219
220 def _setup_failing_update_early(n: int) -> tuple[tuple[t.Any, ...], dict[str, t.Any]]:
221 return (
222 (
223 INT_BIDICTS_BY_LEN[n].copy(),
224 INT_DICTS_BY_LEN_DUPVAL_EARLY[n],
225 INT_DICTS_BY_LEN[n],
226 ),
227 {},
228 )
229
230
231 def _setup_failing_update_late(n: int) -> tuple[tuple[t.Any, ...], dict[str, t.Any]]:
232 return (
233 (
234 INT_BIDICTS_BY_LEN[n].copy(),
235 INT_DICTS_BY_LEN_DUPVAL_LATE[n],
236 INT_DICTS_BY_LEN[n],
237 ),
238 {},
239 )
240
241
242 @pytest.mark.parametrize('kind', DATASET_NAMES)
243 @pytest.mark.parametrize('n', LENS)
244 def test_bi_init_from_dict(kind: str, n: int, benchmark: t.Any) -> None:
245 """Benchmark initializing a new bidict from a dict."""
246 other = DICTS_BY_KIND_AND_LEN[kind][n]
247 benchmark.pedantic(bidict.bidict, args=(other,), rounds=ROUNDS, iterations=scaled_iterations(n))
248
249
250 @pytest.mark.parametrize('n', LENS)
251 def test_bi_init_from_bi(n: int, benchmark: t.Any) -> None:
252 """Benchmark initializing a bidict from another bidict."""
253 other = INT_BIDICTS_BY_LEN[n]
254 benchmark.pedantic(bidict.bidict, args=(other,), rounds=ROUNDS, iterations=scaled_iterations(n))
255
256
257 @pytest.mark.parametrize('n', LENS)
258 def test_bi_init_fail_early_dupval(n: int, benchmark: t.Any) -> None:
259 """Benchmark failing initialization when a duplicate value appears near the start."""
260 other = INT_DICTS_BY_LEN_DUPVAL_EARLY[n]
261
262 def failing_init() -> None:
263 with pytest.raises(bidict.DuplicationError):
264 bidict.bidict(other)
265
266 benchmark.pedantic(failing_init, rounds=ROUNDS, iterations=scaled_iterations(n))
267
268
269 @pytest.mark.parametrize('n', LENS)
270 def test_bi_init_fail_late_dupval(n: int, benchmark: t.Any) -> None:
271 """Benchmark failing initialization when a duplicate value appears at the end."""
272 other = INT_DICTS_BY_LEN_DUPVAL_LATE[n]
273
274 def failing_init() -> None:
275 with pytest.raises(bidict.DuplicationError):
276 bidict.bidict(other)
277
278 benchmark.pedantic(failing_init, rounds=ROUNDS, iterations=scaled_iterations(n))
279
280
281 @pytest.mark.parametrize('kind', DATASET_NAMES)
282 @pytest.mark.parametrize('n', LENS)
283 def test_bi_getitem_present(kind: str, n: int, benchmark: t.Any) -> None:
284 """Benchmark forward lookup of an existing key."""
285 bi = BIDICTS_BY_KIND_AND_LEN[kind][n]
286 key, val = LOOKUP_ITEMS_BY_KIND_AND_LEN[kind][n]
287 result = benchmark.pedantic(bi.__getitem__, args=(key,), rounds=ROUNDS, iterations=CHEAP_ITERATIONS)
288 assert result == val
289
290
291 @pytest.mark.parametrize('kind', DATASET_NAMES)
292 @pytest.mark.parametrize('n', LENS)
293 def test_bi_inverse_getitem_present(kind: str, n: int, benchmark: t.Any) -> None:
294 """Benchmark inverse lookup of an existing value."""
295 bi = BIDICTS_BY_KIND_AND_LEN[kind][n]
296 key, val = LOOKUP_ITEMS_BY_KIND_AND_LEN[kind][n]
297 result = benchmark.pedantic(bi.inverse.__getitem__, args=(val,), rounds=ROUNDS, iterations=CHEAP_ITERATIONS)
298 assert result == key
299
300
301 @pytest.mark.parametrize('n', LENS)
302 def test_bi_setitem_new_item(n: int, benchmark: t.Any) -> None:
303 """Benchmark inserting new items into an existing bidict."""
304 benchmark.pedantic(
305 _setitem,
306 setup=lambda n=n: _setup_setitem_new(n),
307 teardown=_assert_mapping_matches,
308 rounds=ROUNDS,
309 )
310
311
312 @pytest.mark.parametrize('n', LENS)
313 def test_bi_setitem_replace_existing_key(n: int, benchmark: t.Any) -> None:
314 """Benchmark replacing the values of existing keys with new unique values."""
315 benchmark.pedantic(
316 _setitem,
317 setup=lambda n=n: _setup_setitem_replace_existing_key(n),
318 teardown=_assert_mapping_matches,
319 rounds=ROUNDS,
320 )
321
322
323 @pytest.mark.parametrize('n', LENS)
324 def test_bi_forceput_existing_value(n: int, benchmark: t.Any) -> None:
325 """Benchmark forceput when each provided value is already associated with another key."""
326 benchmark.pedantic(
327 _forceput,
328 setup=lambda n=n: _setup_forceput_existing_value(n),
329 teardown=_assert_mapping_matches,
330 rounds=ROUNDS,
331 )
332
333
334 @pytest.mark.parametrize('n', LENS)
335 def test_bi_pop_existing_key(n: int, benchmark: t.Any) -> None:
336 """Benchmark popping existing keys."""
337 benchmark.pedantic(
338 _pop,
339 setup=lambda n=n: _setup_pop(n),
340 teardown=_assert_mapping_matches,
341 rounds=ROUNDS,
342 )
343
344
345 @pytest.mark.parametrize('n', LENS)
346 def test_bi_update_partial_overlap(n: int, benchmark: t.Any) -> None:
347 """Benchmark updating from a mapping with a mix of overlapping and new items."""
348 benchmark.pedantic(
349 _update,
350 setup=lambda n=n: _setup_update_partial_overlap(n),
351 teardown=_assert_mapping_matches,
352 rounds=ROUNDS,
353 )
354
355
356 @pytest.mark.parametrize('n', LENS)
357 def test_bi_update_fail_early_dupval(n: int, benchmark: t.Any) -> None:
358 """Benchmark a bulk update that fails near the start and rolls back."""
359 benchmark.pedantic(
360 _failing_update,
361 setup=lambda n=n: _setup_failing_update_early(n),
362 teardown=_assert_mapping_matches,
363 rounds=ROUNDS,
364 )
365
366
367 @pytest.mark.parametrize('n', LENS)
368 def test_bi_update_fail_late_dupval(n: int, benchmark: t.Any) -> None:
369 """Benchmark a bulk update that fails at the end and rolls back."""
370 benchmark.pedantic(
371 _failing_update,
372 setup=lambda n=n: _setup_failing_update_late(n),
373 teardown=_assert_mapping_matches,
374 rounds=ROUNDS,
375 )
376
377
378 @pytest.mark.parametrize('n', LENS)
379 def test_bi_iter(n: int, benchmark: t.Any) -> None:
380 """Benchmark iterating over a bidict."""
381 bi = INT_BIDICTS_BY_LEN[n]
382 # Build the iterator inside the timed callable: one pre-built and passed via args
383 # would already be exhausted by the second of the repeated calls below.
384 benchmark.pedantic(lambda: consume(iter(bi)), rounds=ROUNDS, iterations=scaled_iterations(n))
385
386
387 @pytest.mark.parametrize('n', LENS)
388 def test_orderedbi_iter(n: int, benchmark: t.Any) -> None:
389 """Benchmark iterating over an OrderedBidict."""
390 ob = ORDERED_BIDICTS_BY_LEN[n]
391 # Build the iterator inside the timed callable: one pre-built and passed via args
392 # would already be exhausted by the second of the repeated calls below.
393 benchmark.pedantic(lambda: consume(iter(ob)), rounds=ROUNDS, iterations=scaled_iterations(n))
394
395
396 @pytest.mark.parametrize('n', LENS)
397 def test_bi_equals_with_equal_dict(n: int, benchmark: t.Any) -> None:
398 """Benchmark bidict.__eq__ with an equivalent dict."""
399 bi, d = BIDICT_AND_DICT_LAST_TWO_ITEMS_DIFFERENT_ORDER[n]
400 result = benchmark.pedantic(bi.__eq__, args=(d,), rounds=ROUNDS, iterations=scaled_iterations(n))
401 assert result
402
403
404 @pytest.mark.parametrize('n', LENS)
405 def test_orderedbi_items_equals_with_equal_dict_items(n: int, benchmark: t.Any) -> None:
406 """Benchmark OrderedBidict.items().__eq__ with equivalent dict_items."""
407 ob, d = ORDERED_BIDICT_AND_DICT_LAST_TWO_ITEMS_DIFFERENT_ORDER[n]
408 result = benchmark.pedantic(ob.items().__eq__, args=(d.items(),), rounds=ROUNDS, iterations=scaled_iterations(n))
409 assert result
410
411
412 @pytest.mark.parametrize('n', LENS)
413 def test_copy(n: int, benchmark: t.Any) -> None:
414 """Benchmark creating a copy of a bidict."""
415 bi = INT_BIDICTS_BY_LEN[n]
416 benchmark.pedantic(bi.copy, rounds=ROUNDS, iterations=scaled_iterations(n))
417
418
419 @pytest.mark.parametrize('n', LENS)
420 def test_pickle(n: int, benchmark: t.Any) -> None:
421 """Benchmark pickling a bidict."""
422 bi = INT_BIDICTS_BY_LEN[n]
423 benchmark.pedantic(pickle.dumps, args=(bi,), rounds=ROUNDS, iterations=scaled_iterations(n))
424
425
426 @pytest.mark.parametrize('n', LENS)
427 def test_unpickle(n: int, benchmark: t.Any) -> None:
428 """Benchmark unpickling a bidict."""
429 bp = pickle.dumps(INT_BIDICTS_BY_LEN[n])
430 benchmark.pedantic(pickle.loads, args=(bp,), rounds=ROUNDS, iterations=scaled_iterations(n))