SenexCrenshaw / StreamMaster

MIT License
159 stars 20 forks source link

Updates to reduce CPU utilization #175

Closed jbf154 closed 7 months ago

jbf154 commented 7 months ago

Description

Updates to write the stream contents to the circular buffer is chunks instead of one byte at a time. When reading from the buffer, wait until data is available instead of polling & using semaphores.

Issues Fixed or Closed

Type of Change

Please delete options that are not relevant.

Checklist

SenexCrenshaw commented 7 months ago

int dataInBuffer = (_writeIndex - _oldestDataIndex + _buffer.Length) % _buffer.Length;

This line calculates the amount of data in the buffer assuming a circular buffer. Here's the breakdown:

_writeIndex - _oldestDataIndex: This calculates the difference between where data is being written and the oldest data in the buffer. If _writeIndex is ahead of _oldestDataIndex, this gives the size of the data between them. Adding _buffer.Length: This ensures that the result is positive even if _oldestDataIndex is greater than _writeIndex (which can happen in a circular buffer). Taking the modulo % _buffer.Length: This adjusts the result to be within the bounds of the buffer size.

int dataInBuffer = _oldestDataIndex > 0 ? _buffer.Length : _writeIndex;

This line uses a ternary operator to set dataInBuffer:

If _oldestDataIndex is greater than 0, it sets dataInBuffer to _buffer.Length. This seems to assume that if the oldest data index is not at the start of the buffer, the buffer is completely full. If _oldestDataIndex is 0 or less, it sets dataInBuffer to _writeIndex. This seems to assume that all data from the start of the buffer to _writeIndex is valid, ignoring _oldestDataIndex. In summary, the first line accurately calculates the amount of data in a circular buffer, while the second line makes a simplified assumption that might not always hold true, especially in a circular buffer scenario where _oldestDataIndex and _writeIndex can vary independently.

SenexCrenshaw commented 7 months ago

not sure why you think it is using a lot of cpu. maybe we can start from there.