-
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathbenchmark.py
More file actions
371 lines (280 loc) · 9.16 KB
/
benchmark.py
File metadata and controls
371 lines (280 loc) · 9.16 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import asyncio
from functools import partial
from typing import Any, Callable
import pytest
from async_lru import _LRUCacheWrapper, alru_cache
try:
from pytest_codspeed import BenchmarkFixture
except ImportError: # pragma: no branch # only hit in cibuildwheel
pytestmark = pytest.mark.skip("pytest-codspeed needs to be installed")
else:
pytestmark = pytest.mark.benchmark
@pytest.fixture
def loop():
# Save current loop to restore after the test
try:
old_loop = asyncio.get_running_loop()
except RuntimeError:
old_loop = None
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
yield new_loop
new_loop.close()
if old_loop is not None:
asyncio.set_event_loop(old_loop)
@pytest.fixture
def run_loop(loop):
async def _get_coro(awaitable):
"""A helper function that turns an awaitable into a coroutine."""
return await awaitable
def run_the_loop(fn, *args, **kwargs):
awaitable = fn(*args, **kwargs)
coro = awaitable if asyncio.iscoroutine(awaitable) else _get_coro(awaitable)
return loop.run_until_complete(coro)
return run_the_loop
# Bounded cache (LRU)
async def _cached_func(x):
return x
def create_cached_func():
return alru_cache(maxsize=128)(_cached_func)
async def _cached_func_ttl(x):
return x
def create_cached_func_ttl():
return alru_cache(maxsize=16, ttl=0.01)(_cached_func_ttl)
# Unbounded cache (no maxsize)
async def _cached_func_unbounded(x):
return x
def create_cached_func_unbounded():
return alru_cache()(_cached_func_unbounded)
async def _cached_func_unbounded_ttl(x):
return x
def create_cached_func_unbounded_ttl():
return alru_cache(ttl=0.01)(_cached_func_unbounded_ttl)
def create_cached_meth():
class MethodsInstance:
@alru_cache(maxsize=128)
async def cached_meth(self, x):
return x
return MethodsInstance().cached_meth
def create_cached_meth_ttl():
class MethodsInstance:
@alru_cache(maxsize=16, ttl=0.01)
async def cached_meth_ttl(self, x):
return x
return MethodsInstance().cached_meth_ttl
def create_cached_meth_unbounded():
class MethodsInstance:
@alru_cache()
async def cached_meth_unbounded(self, x):
return x
return MethodsInstance().cached_meth_unbounded
def create_cached_meth_unbounded_ttl():
class MethodsInstance:
@alru_cache(ttl=0.01)
async def cached_meth_unbounded_ttl(self, x):
return x
return MethodsInstance().cached_meth_unbounded_ttl
async def uncached_func(x):
return x
funcs_no_ttl = [
create_cached_func,
create_cached_func_unbounded,
create_cached_meth,
create_cached_meth_unbounded,
]
no_ttl_ids = [
"func-bounded",
"func-unbounded",
"meth-bounded",
"meth-unbounded",
]
funcs_ttl = [
create_cached_func_ttl,
create_cached_func_unbounded_ttl,
create_cached_meth_ttl,
create_cached_meth_unbounded_ttl,
]
ttl_ids = [
"func-bounded-ttl",
"func-unbounded-ttl",
"meth-bounded-ttl",
"meth-unbounded-ttl",
]
all_funcs = [*funcs_no_ttl, *funcs_ttl]
all_ids = [*no_ttl_ids, *ttl_ids]
@pytest.mark.parametrize("factory", all_funcs, ids=all_ids)
def test_cache_hit_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
factory: Callable[[], _LRUCacheWrapper[Any]],
) -> None:
func = factory()
keys = list(range(10))
for key in keys:
run_loop(func, key)
async def run() -> None:
for _ in range(100):
for key in keys:
await func(key)
benchmark(run_loop, run)
@pytest.mark.parametrize("factory", all_funcs, ids=all_ids)
def test_cache_miss_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
factory: Callable[[], _LRUCacheWrapper[Any]],
) -> None:
func = factory()
# Use 2048 objects (16x maxsize=128) to force evictions and measure actual misses
unique_objects = [object() for _ in range(2048)]
async def run() -> None:
for obj in unique_objects:
await func(obj)
benchmark(run_loop, run)
@pytest.mark.parametrize("factory", all_funcs, ids=all_ids)
def test_cache_clear_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
factory: Callable[[], _LRUCacheWrapper[Any]],
) -> None:
func = factory()
for i in range(100):
run_loop(func, i)
benchmark(func.cache_clear)
@pytest.mark.parametrize("factory", funcs_ttl, ids=ttl_ids)
def test_cache_ttl_expiry_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
factory: Callable[[], _LRUCacheWrapper[Any]],
) -> None:
func_ttl = factory()
run_loop(func_ttl, 99)
run_loop(asyncio.sleep, 0.02)
benchmark(run_loop, func_ttl, 99)
@pytest.mark.parametrize("factory", all_funcs, ids=all_ids)
def test_cache_invalidate_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
factory: Callable[[], _LRUCacheWrapper[Any]],
) -> None:
func = factory()
keys = list(range(123, 321))
for i in keys:
run_loop(func, i)
invalidate = func.cache_invalidate
@benchmark
def run() -> None:
for i in keys:
invalidate(i)
@pytest.mark.parametrize("factory", all_funcs, ids=all_ids)
def test_cache_info_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
factory: Callable[[], _LRUCacheWrapper[Any]],
) -> None:
func = factory()
keys = list(range(1000))
for i in keys:
run_loop(func, i)
cache_info = func.cache_info
@benchmark
def run() -> None:
for _ in keys:
cache_info()
@pytest.mark.parametrize("factory", all_funcs, ids=all_ids)
def test_concurrent_cache_hit_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
factory: Callable[[], _LRUCacheWrapper[Any]],
) -> None:
func = factory()
keys = list(range(600, 700))
for key in keys:
run_loop(func, key)
async def gather_coros():
gather = asyncio.gather
for _ in range(10):
await gather(*map(func, keys))
benchmark(run_loop, gather_coros)
def test_cache_fill_eviction_benchmark(
benchmark: BenchmarkFixture, run_loop: Callable[..., Any]
) -> None:
func = create_cached_func()
for i in range(-128, 0):
run_loop(func, i)
keys = list(range(5000))
async def fill():
for k in keys:
await func(k)
benchmark(run_loop, fill)
# ===========================
# Internal Microbenchmarks
# ===========================
# These benchmarks directly exercise internal (sync) methods and data structures
# not covered by the async public API benchmarks above.
# The relevant internal methods do not exist on _LRUCacheWrapperInstanceMethod,
# so we can skip methods for this part of the benchmark suite.
# We also skip wrappers with ttl because it raises KeyError.
only_funcs_no_ttl = funcs_no_ttl[:2]
func_ids_no_ttl = no_ttl_ids[:2]
@pytest.mark.parametrize("factory", only_funcs_no_ttl, ids=func_ids_no_ttl)
def test_internal_cache_hit_microbenchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
factory: Callable[[], _LRUCacheWrapper[Any]],
) -> None:
"""Directly benchmark _cache_hit (internal, sync) using parameterized funcs."""
func = factory()
cache_hit = func._cache_hit
keys = list(range(128))
for i in keys:
run_loop(func, i)
@benchmark
def run() -> None:
for i in keys:
cache_hit(i)
@pytest.mark.parametrize("factory", only_funcs_no_ttl, ids=func_ids_no_ttl)
def test_internal_cache_miss_microbenchmark(
benchmark: BenchmarkFixture, factory: Callable[[], _LRUCacheWrapper[Any]]
) -> None:
"""Directly benchmark _cache_miss (internal, sync) using parameterized funcs."""
func = factory()
cache_miss = func._cache_miss
@benchmark
def run() -> None:
for i in range(128):
cache_miss(i)
@pytest.mark.parametrize("factory", only_funcs_no_ttl, ids=func_ids_no_ttl)
@pytest.mark.parametrize("task_state", ["finished", "cancelled", "exception"])
def test_internal_task_done_callback_microbenchmark(
benchmark: BenchmarkFixture,
loop: asyncio.BaseEventLoop,
factory: Callable[[], _LRUCacheWrapper[Any]],
task_state: str,
) -> None:
"""Directly benchmark _task_done_callback (internal, sync) using parameterized funcs and task states."""
func = factory()
async def dummy_coro():
if task_state == "exception":
raise ValueError("test exception")
return 123
task = loop.create_task(dummy_coro())
if task_state == "finished":
loop.run_until_complete(task)
elif task_state == "cancelled":
task.cancel()
try:
loop.run_until_complete(task)
except asyncio.CancelledError:
pass
elif task_state == "exception":
try:
loop.run_until_complete(task)
except Exception:
pass
iterations = range(1000)
callback_fn = func._task_done_callback
@benchmark
def run() -> None:
for i in iterations:
callback = partial(callback_fn, i)
callback(task)