Last active
December 7, 2015 15:42
-
-
Save awesomebytes/f53ddf0ae43563fe55ee to your computer and use it in GitHub Desktop.
Python ring buffer
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
| import numpy as np | |
| class RingBuffer(): | |
| "A 1D ring buffer using numpy arrays" | |
| def __init__(self, length): | |
| self.data = np.zeros(length, dtype='f') | |
| self.index = 0 | |
| def extend(self, x): | |
| "adds array x to ring buffer" | |
| x_index = (self.index + 1) % self.data.size | |
| self.data[x_index] = x | |
| self.index = x_index | |
| def get(self): | |
| "Returns the first-in-first-out data in the ring buffer" | |
| idx = (self.index + np.arange(self.data.size)) % self.data.size | |
| return self.data[idx] | |
| def to_list(self): | |
| l = [] | |
| for i in range(self.index, self.data.size): | |
| l.append(self.data[i]) | |
| for i in range(0, self.index): | |
| l.append(self.data[i]) | |
| return l | |
| if __name__ == '__main__': | |
| my_buffer = RingBuffer(10) | |
| import time | |
| while True: | |
| for v in range(100): | |
| my_buffer.extend(v) | |
| print('Ring buffer looks like:') | |
| print(my_buffer.to_list()) | |
| time.sleep(0.1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment