Created
March 7, 2025 15:52
-
-
Save p1-dta/f86409dc4f77c40453691e4aca9aa261 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# requires-python = ">=3.13" | |
# dependencies = [ | |
# "more-itertools>=10.6.0", | |
# "pytest>=8.3.5", | |
# "pytest-benchmark>=5.1.0", | |
# ] | |
import collections | |
import statistics | |
import more_itertools | |
import pytest | |
def performance(values: list[float], window_size: int) -> collections.abc.Generator[float]: | |
fifo = collections.deque() | |
values_iterator = iter(values) | |
sigma = 0 | |
for _ in range(min(len(values), window_size)): | |
value = next(values_iterator) | |
sigma += value | |
fifo.append(value) | |
yield sigma / window_size | |
for value in values_iterator: | |
sigma += value | |
sigma -= fifo.popleft() | |
fifo.append(value) | |
yield sigma / window_size | |
def readability(values: list[float], window_size: int) -> collections.abc.Generator[float]: | |
for window in more_itertools.windowed(values, window_size): | |
yield statistics.mean(window) | |
@pytest.mark.parametrize( | |
"implementation", | |
[ | |
performance, | |
readability, | |
] | |
) | |
def test_implementation(implementation): | |
assert ( | |
list(implementation(range(5), 2)) | |
== [0.5, 1.5, 2.5, 3.5] | |
) | |
@pytest.mark.parametrize( | |
("implementation"), | |
[ | |
performance, | |
readability, | |
] | |
) | |
def test_benchmark_100(benchmark, implementation): | |
benchmark(lambda x, y: collections.deque(implementation(x, y), maxlen=0), range(100), 10) | |
@pytest.mark.parametrize( | |
("implementation"), | |
[ | |
performance, | |
readability, | |
] | |
) | |
def test_benchmark_1000(benchmark, implementation): | |
benchmark(lambda x, y: collections.deque(implementation(x, y), maxlen=0), range(1_000), 100) | |
@pytest.mark.parametrize( | |
("implementation"), | |
[ | |
performance, | |
readability, | |
] | |
) | |
def test_benchmark_10_000(benchmark, implementation): | |
benchmark(lambda x, y: collections.deque(implementation(x, y), maxlen=0), range(10_000), 1_000) |
Author
p1-dta
commented
Mar 7, 2025
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment