1. import time
  2. import sys
  3. class TimestampBuffer:
  4. def __init__(self, buffer_size=100):
  5. """
  6. Initializes the timestamp buffer.
  7. Args:
  8. buffer_size (int): The maximum number of timestamps to store.
  9. """
  10. self.buffer = []
  11. self.buffer_size = buffer_size
  12. def buffer_timestamp(self, timestamp):
  13. """
  14. Buffers a timestamp.
  15. Args:
  16. timestamp (float or int): The timestamp to buffer.
  17. """
  18. self.buffer.append(timestamp)
  19. if len(self.buffer) > self.buffer_size:
  20. self.buffer.pop(0) # Remove the oldest timestamp
  21. def get_buffer(self):
  22. """
  23. Returns the current buffer of timestamps.
  24. Returns:
  25. list: A list of timestamps.
  26. """
  27. return self.buffer
  28. def clear_buffer(self):
  29. """
  30. Clears the buffer.
  31. """
  32. self.buffer = []
  33. if __name__ == '__main__':
  34. # Example usage:
  35. buffer = TimestampBuffer(buffer_size=5)
  36. # Simulate receiving timestamps
  37. for i in range(15):
  38. timestamp = time.time()
  39. buffer.buffer_timestamp(timestamp)
  40. print(f"Buffered timestamp: {timestamp}")
  41. # Get the buffer content
  42. timestamps = buffer.get_buffer()
  43. print(f"Buffer content: {timestamps}")
  44. #Clear the buffer
  45. buffer.clear_buffer()
  46. print(f"Buffer cleared: {buffer.get_buffer()}")

Add your comment