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
|
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():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
yield loop
loop.close()
@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)
@alru_cache(maxsize=128)
async def cached_func(x):
return x
@alru_cache(maxsize=16, ttl=0.01)
async def cached_func_ttl(x):
return x
# Unbounded cache (no maxsize)
@alru_cache()
async def cached_func_unbounded(x):
return x
@alru_cache(ttl=0.01)
async def cached_func_unbounded_ttl(x):
return x
class Methods:
@alru_cache(maxsize=128)
async def cached_meth(self, x):
return x
@alru_cache(maxsize=16, ttl=0.01)
async def cached_meth_ttl(self, x):
return x
@alru_cache()
async def cached_meth_unbounded(self, x):
return x
@alru_cache(ttl=0.01)
async def cached_meth_unbounded_ttl(self, x):
return x
async def uncached_func(x):
return x
funcs_no_ttl = [
cached_func,
cached_func_unbounded,
Methods.cached_meth,
Methods.cached_meth_unbounded,
]
no_ttl_ids = [
"func-bounded",
"func-unbounded",
"meth-bounded",
"meth-unbounded",
]
funcs_ttl = [
cached_func_ttl,
cached_func_unbounded_ttl,
Methods.cached_meth_ttl,
Methods.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("func", all_funcs, ids=all_ids)
def test_cache_hit_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
func: _LRUCacheWrapper[Any],
) -> None:
# Populate cache
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("func", all_funcs, ids=all_ids)
def test_cache_miss_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
func: _LRUCacheWrapper[Any],
) -> None:
unique_objects = [object() for _ in range(128)]
func.cache_clear()
async def run() -> None:
for obj in unique_objects:
await func(obj)
benchmark(run_loop, run)
@pytest.mark.parametrize("func", all_funcs, ids=all_ids)
def test_cache_clear_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
func: _LRUCacheWrapper[Any],
) -> None:
for i in range(100):
run_loop(func, i)
benchmark(func.cache_clear)
@pytest.mark.parametrize("func_ttl", funcs_ttl, ids=ttl_ids)
def test_cache_ttl_expiry_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
func_ttl: _LRUCacheWrapper[Any],
) -> None:
run_loop(func_ttl, 99)
run_loop(asyncio.sleep, 0.02)
benchmark(run_loop, func_ttl, 99)
@pytest.mark.parametrize("func", all_funcs, ids=all_ids)
def test_cache_invalidate_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
func: _LRUCacheWrapper[Any],
) -> None:
# Populate cache
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("func", all_funcs, ids=all_ids)
def test_cache_info_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
func: _LRUCacheWrapper[Any],
) -> None:
# Populate cache
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("func", all_funcs, ids=all_ids)
def test_concurrent_cache_hit_benchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
func: _LRUCacheWrapper[Any],
) -> None:
# Populate cache
keys = list(range(600, 700))
for key in keys:
run_loop(func, key)
async def gather_coros():
gather = asyncio.gather
for _ in range(10):
return await gather(*map(func, keys))
benchmark(run_loop, gather_coros)
def test_cache_fill_eviction_benchmark(
benchmark: BenchmarkFixture, run_loop: Callable[..., Any]
) -> None:
# Populate cache
for i in range(-128, 0):
run_loop(cached_func, i)
keys = list(range(5000))
async def fill():
for k in keys:
await cached_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 = all_funcs[:2]
func_ids_no_ttl = all_ids[:2]
@pytest.mark.parametrize("func", only_funcs_no_ttl, ids=func_ids_no_ttl)
def test_internal_cache_hit_microbenchmark(
benchmark: BenchmarkFixture,
run_loop: Callable[..., Any],
func: _LRUCacheWrapper[Any],
) -> None:
"""Directly benchmark _cache_hit (internal, sync) using parameterized funcs."""
cache_hit = func._cache_hit
# Populate cache
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("func", only_funcs_no_ttl, ids=func_ids_no_ttl)
def test_internal_cache_miss_microbenchmark(
benchmark: BenchmarkFixture, func: _LRUCacheWrapper[Any]
) -> None:
"""Directly benchmark _cache_miss (internal, sync) using parameterized funcs."""
cache_miss = func._cache_miss
@benchmark
def run() -> None:
for i in range(128):
cache_miss(i)
@pytest.mark.parametrize("func", 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,
func: _LRUCacheWrapper[Any],
task_state: str,
) -> None:
"""Directly benchmark _task_done_callback (internal, sync) using parameterized funcs and task states."""
# Create a dummy coroutine and task
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)
|