Skip to content

Instantly share code, notes, and snippets.

@markpapadakis
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save markpapadakis/ec87312c464cd5df85c5 to your computer and use it in GitHub Desktop.

Select an option

Save markpapadakis/ec87312c464cd5df85c5 to your computer and use it in GitHub Desktop.
template<typename T>
void SimpleMovingAverage(const T *const timeSeries, const uint32_t timeSeriesCnt, const uint32_t windowSize, Vector<T> &res)
{
T window[128], sum = 0;
uint8_t windowIndex, windowBase = 0;
uint32_t i = 0;
const auto n = Min<uint32_t>(timeSeriesCnt, windowSize - 1);
runtime_assert(windowSize <= ARRAY_SIZE(window), "Too large window");
static_assert((ARRAY_SIZE(window)&(ARRAY_SIZE(window) - 1)) == 0, "window size not base 2");
res.EnsureCapacity(timeSeriesCnt / windowSize);
while (i != n)
{
const auto v = timeSeries[i];
window[i] = v;
sum+=v;
++i;
res.Append(sum / i);
}
for (windowIndex = i; i != timeSeriesCnt; ++i)
{
const auto v = timeSeries[i];
window[windowIndex] = v;
sum+=v;
windowIndex = (windowIndex + 1)&(ARRAY_SIZE(window) - 1);
sum-=window[windowBase];
windowBase = (windowBase + 1)&(ARRAY_SIZE(window) - 1);
res.Append(sum / windowSize);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment