runningavg

Keep a running calculation of the average value of a series

Returns New average value
Keys
  1. Key to store the current average
  2. Key to store the current count of values
Args
  1. Next value in the series

Description

This script can be used to keep a running average of a series of values, without needing to keep each of the individual values around.

Example

> evalsha 399fddde578fd9cb924edce746c783e8340d8251 2 score:avg score:count 80
"80"
> evalsha 399fddde578fd9cb924edce746c783e8340d8251 2 score:avg score:count 100
"90"
> evalsha 399fddde578fd9cb924edce746c783e8340d8251 2 score:avg score:count 75
"85"
> evalsha 399fddde578fd9cb924edce746c783e8340d8251 2 score:avg score:count 98
"88.25"
> evalsha 399fddde578fd9cb924edce746c783e8340d8251 2 score:avg score:count 98
"90.2"
> evalsha 399fddde578fd9cb924edce746c783e8340d8251 2 score:avg score:count 98
"91.5"
> get score:avg
"91.5"
> get score:count
"6"

Source

local currentval = tonumber(redis.call('get', KEYS[1])) or 0
local count = redis.call('incr', KEYS[2])

currentval = tostring(currentval * (count - 1)/count + (ARGV[1]/count))

redis.call('set', KEYS[1], currentval)
return currentval

SHA

399fddde578fd9cb924edce746c783e8340d8251

Explore Your Redis Memory Usage with an Interactive Map

Memetria shows you large keys, memory leaks, old keys, and other potential problems quickly. Try it today without a credit card.

Last updated 14 Aug 2014.

← More scripts from the Memetria Library

License

All scripts on this site are in the public domain, unless otherwise noted, and are provided without warranty express or implied. Memetria make no claim for the effectiveness, safety, security or quality of the scripts contained within.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.