Skip to content

Commit 1240e61

Browse files
authored
Optimize get_window_ranges function (#489)
deque.appendleft is roughly 10x faster than list.insert(0, ...)
1 parent be120a3 commit 1240e61

File tree

2 files changed

+10
-10
lines changed
  • quixstreams/dataframe/windows
  • tests/test_quixstreams/test_dataframe/test_windows

2 files changed

+10
-10
lines changed

quixstreams/dataframe/windows/base.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from typing import Any, Optional, Callable, Tuple, List
1+
from collections import deque
2+
from typing import Any, Deque, Optional, Callable, Tuple
23

34
from typing_extensions import TypedDict
45

@@ -17,7 +18,7 @@ class WindowResult(TypedDict):
1718

1819
def get_window_ranges(
1920
timestamp_ms: int, duration_ms: int, step_ms: Optional[int] = None
20-
) -> List[Tuple[int, int]]:
21+
) -> Deque[Tuple[int, int]]:
2122
"""
2223
Get a list of window ranges for the given timestamp.
2324
:param timestamp_ms: timestamp in milliseconds
@@ -28,14 +29,14 @@ def get_window_ranges(
2829
if not step_ms:
2930
step_ms = duration_ms
3031

31-
window_ranges = []
32+
window_ranges = deque()
3233
current_window_start = timestamp_ms - (timestamp_ms % step_ms)
3334

3435
while (
3536
current_window_start > timestamp_ms - duration_ms and current_window_start >= 0
3637
):
3738
window_end = current_window_start + duration_ms
38-
window_ranges.insert(0, (current_window_start, window_end))
39+
window_ranges.appendleft((current_window_start, window_end))
3940
current_window_start -= step_ms
4041

4142
return window_ranges

tests/test_quixstreams/test_dataframe/test_windows/test_base.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,10 @@ class TestGetWindowRanges:
1616
],
1717
)
1818
def test_get_window_ranges_with_step(self, timestamp, duration, step, expected):
19-
assert (
20-
get_window_ranges(
21-
timestamp_ms=timestamp, duration_ms=duration, step_ms=step
22-
)
23-
== expected
19+
result = get_window_ranges(
20+
timestamp_ms=timestamp, duration_ms=duration, step_ms=step
2421
)
22+
assert list(result) == expected
2523

2624
@pytest.mark.parametrize(
2725
"timestamp, duration, expected",
@@ -31,4 +29,5 @@ def test_get_window_ranges_with_step(self, timestamp, duration, step, expected):
3129
],
3230
)
3331
def test_get_window_ranges_no_step(self, timestamp, duration, expected):
34-
assert get_window_ranges(timestamp, duration) == expected
32+
result = get_window_ranges(timestamp, duration)
33+
assert list(result) == expected

0 commit comments

Comments
 (0)