As @ukmoose already mentioned, you could indeed have a look at the code of my speed node. It makes use of the circular-buffer NPM module.
- I create a ring buffer, with length = 1 cell for each second. E.g. when the user specifies "speed per minute", then I create 60 cells.
- Every second I count the number of messages that have arrived during the last second, and I store that count into the next cell.
- Then I move the pointer to the next cell.
- That process continues every second. After 1 minute you will start overwriting old values ...
So at any moment the sum of the values in ALL cells = total number of messages arrived during the last minute. When you divide that sum by 60, you have the average number of messages per second.
However, calculating the sum of all cells every second would be very inefficient. So I use a simple trick to calculate the sum:
- As mentioned above, the messages are counted every second.
- Then the sum is recalculated, based on that new count and the old count (which is stored currently in the cell and will be overwritten in the next step):
sum = sum - old_counter + new_counter
- Store the new counter in the cell
So I remove old counters from the sum and add new counters to the sum. That way the sum always contains the sum of all cells, without having to loop all the cells. This is particulary interesting when you have a large number of cells ...