I'm working in an application where there is a lot of reporting of external events. One of the metrics that is used often is the event rate as a function of time. For example, measuring the sample-rate of some external asynchronous sensor.
Currently the way I'm calculating the frequency of events like this is to keep a queue of event timestamps. When the event occurs we push a current timestamp onto the queue, then pop until the oldest timestamp is less than a predefined age. Then, the event frequency is proportional to the size of the queue. In pseudo-code the method usually looks something like this:
def on_event():
var now = current_time()
time_queue.push(now)
while((now - time_queue.front()) > QUEUE_DEPTH_SECONDS):
time_queue.pop()
frequency = time_queue.size() / QUEUE_DEPTH_SECONDS
Now this approach is obviously not optimal:
- Memory requirement and computation time is proportional to event rate.
- The queue duration has to be manually adjusted based on the expected data rate in order to tune low-frequency performance vs memory requirements.
- The response-time of the frequency measurement is also dependent on the queue duration. Longer durations lower the response time of the calculation.
- The frequency is only updated when a new event occurs. If the events stop occurring, then the frequency measurement will remain at the value calculated when the last event was received.
I'm curious if there are any alternative algorithms that can be used to calculate the rate of an event, and what trade-offs they have in relation to computational complexity, space requirements, response-time, etc.