Possible Duplicate:
C#. Need to optimise counting positive and negative values
I need to maximize speed of the following functionality:
- a. a value comes in. value has 2 properties – int value and long timestamp in ticks.
- b. need to count previously stored values which are younger than 1ms (from the current).
- c. need to count negative and positive separately.
- d. i only need to know if there are either 10 neg or pos values. i dont need to keep any other knowledge of the values.
me thinks – to implement 2 ring arrays for pos and neg separately, replacing expired with 0 keeping track of pos.neg counts as they come.
any thoughts?
Maintaining 2 buffers to keep the positives separated from the negatives sounds like a pain and inefficient.
You could instead have a single buffer with all the values, and use
std::accumulateto count up the positives and negatives. If you start with a collection of all the tuples (each of which has an age and a value), you could begin by sorting the collection according to age, finding the last element that is <= 1 ms old, and then usingaccumulatefrombegin()to that point. Here’s some code that demonstrates that last bit:If sorting the collection by age and then searching the sorted results for the last eligible entry sounds too ineficient, you could use
for_each_ifinstead ofaccumulateand simply iterate over the whole collection once.for_each_ifisn’t part of the Standard Library, but it’s easy enough to write. If you don’t want to muck about with writing your ownfor_each_ifthat’s fine, too. You could simply tweak the accumulator a bit so that it doesn’t accumulate elements which are too old: