TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Ring buffers and moving averages

3 pointsby megalodonalmost 9 years ago

1 comment

nostrademonsalmost 9 years ago
You can actually calculate the moving average in constant time with a ring buffer, such that you don&#x27;t have to iterate over the whole buffer to compute it each time a new element is added. Just store the sum &amp; size with the buffer. As an element is overwritten, subtract it from the sum and add its replacement. The average is just the sum &#x2F; size.<p>It&#x27;s a handy trick in financial software, where you often need to calculate relatively small sliding windows over enormously large data streams and latency is critical. The same technique generalizes to any computation that can be expressed as a fold function where the operation is invertible.