Slice Sorted Python Events by Time with bisect_left
A build timeline has several events at the same elapsed millisecond. A report for the window from 100 to 200 ms should include every event at 100 ms and leave events at 200 ms for the next window. If the timeline is already sorted, two calls to bisect_left() find the slice without scanning all the events for each report.
Find the First Index at Each Boundary
Start with a sorted list of elapsed milliseconds.
bisect_left() finds the first position whose value is at least the target. For 100 it returns the index of the first 100, so the slice includes both copies. For 200 it returns the index of the first 200. Because a Python slice excludes its stop index, both copies of 200 stay outside the result. A boundary between timestamps works the same way. The returned index points to the first later timestamp, or to the end of the list if all values are smaller.
Python bisect documentation
Search Records by Their Timestamp
With Python 3.10 or later, use key to search records directly. Save this helper as event_window.py. It expects a list of (elapsed_ms, event_name) tuples sorted by the first field, with integer boundaries in the same units.
| |
The key function runs on records during the search. It does not run on the boundary arguments, so pass 100 directly as the start value. The helper returns a new list and preserves the order of records with equal timestamps.
Put Shared Boundaries in the Next Window
Save this as show_windows.py beside the helper and run python show_windows.py.
| |
These windows use the rule start_ms <= elapsed_ms < end_ms. The 200 ms events belong to the second window only. Replacing the stop search with bisect_right() would also include them in the first window. Equal start and end values give an empty slice because both searches return the same index.
Keep the Input Sorted Between Queries
Sort incoming records once by elapsed time if they can arrive out of order. Python’s sort preserves the input order of records that share the same sort key. Keep the list stable during a query so the searches and slice see the same data. If you append records later, keep timestamps in nondecreasing order or sort again before querying.
Each search takes logarithmic time on the sorted list. Returning the slice takes time and additional list storage proportional to the number of matching records. When the report only needs a count, the difference stop - first already gives it. For a stream that you read once, filtering each record as it arrives avoids building a list to search.
Test Windows Against a Direct Filter
Save this as test_event_window.py beside the helper and run python test_event_window.py.
| |
The filter states the window rule directly and serves as a reference for the slice. The boundary pairs cover duplicates, gaps between timestamps, empty windows, and windows that extend beyond the recorded events.