![]() ![]() # python -m timeit -r 5 -n 4 -s "import benchmark_circular_buffer as bcb" "bcb.circular_buffer_assignment()" # python -m timeit -r 5 -n 4 -s "import benchmark_circular_buffer as bcb" "bcb.slice_and_copy_assignemnt()" # python -m timeit -s "import benchmark_circular_buffer as bcb" "bcb.circular_buffer()" # python -m timeit -s "import benchmark_circular_buffer as bcb" "bcb.slice_and_copy()" My_throwaway_arr = c_buf_arr.to_array().copy() # this will take O(N) time for the circular buffer because we use numpy.roll() # lets add copying the array to a new numpy.array Rnd_arr = np.random.randint(0, 1e6, 10**8)Ĭ_buf_arr = RecordingQueue1D(rnd_arr.copy(), len(rnd_arr)) Return "tail: " + str(self.queue_tail) + "\narray: " + str(self.rec_queue) # the item we want will be at head + index Loc = (self.queue_tail + 1 + index) % self.max_length Queue_head = (self.queue_tail + 1) % self.max_lengthĭef replace_item_at(self, index: int, new_value: int): Self.queue_tail = (self.queue_tail + 1) % self.max_length # move tail pointer forward then insert at the tail of the queue Return np.roll(self.rec_queue, -head) # this will force a copyĭef enqueue(self, new_data: np.array) -> None: Head = (self.queue_tail + 1) % self.max_length Self.rec_queue = np.append(np.array(object, dtype=np.int64), np.zeros(maxlen-o_len, dtype=np.int64)) ![]() Self.rec_queue = np.array(object, dtype=np.int64) #allocate the memory we need ahead of time ![]() # except to_array which has to copy the array and is O(n)ĭef _init_(self, object: object, maxlen: int): # all operations are O(1) and don't require copying the array Here is an example of the class I created for this circular buffer/array: # benchmark_circular_buffer.py This can be found using the same formula: head = (tail + 1) % length. You can use modulus to make this wrap nicely: new_tail = (old_tail + 1) % length.įinding the head of the queue is always one spot after the tail. x, x, x, x, x, xĮach time you enqueue you move the tail one spot to the right. If you start with this array: x, x, x, x, x, xĪnd you want to drop x and add x you can do this using the originally allocated memory for the array without the need for copy x, x, x, x, x, xĪnd so on. You can use a circular array with a pointer that tracks where the tail is (the place you will be adding new items to the queue). (You will eventually need to do one copy using numpy.roll to pass the final array to another function.) You mentioned "first-in last-out" which is a stack, but your example demonstrates a queue, so I will share a solution for a queue that does not require copying to enqueue new items. I know I'm late and this question has been satisfactorily answered, but I was just facing something similar for recording a buffer of streaming data. ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |