What is the fastest way to calculate a x second rolling average of an array in ruby?
I have two arrays of data from a bicycle ride. The time is when the corresponding speed value was read during the ride. You'll notice that the readings were not taken every second. For this reason I don't believe I can just increment the rolling array by one.
speed = [0, 15, 17, 19, 18, 22, 24, 28, 22, 17, 16, 14, 15, 15, 15, 0, 15, 19, 21, 25, 26, 24, 24]
time = [0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17, 18, 20, 21, 22, 23, 25, 26, 27]
I have tried something like the following (calculates a rolling 5 second average and puts it into an array), but it's pretty slow for large arrays and multiple intervals (takes 8 minutes to calculate all the intervals from a 1 hour bike ride, 1..3600):
duration = time.max
interval_average = []
time_hash = Hash[time.map.with_index.to_a]
roll_start = 0
roll_stop = 5
for i in 1..(duration+1) do
start = time_hash[roll_start]
stop = time_hash[roll_stop]
rolling_array = speed[start..stop]
avg_value = mean(rolling_array)
interval_average.push(avg_value)
roll_start += 1
roll_stop += 1
end
In my own code I'm ignoring the exceptions and pushing 0 instead, as I'm really just interested in finding the max of the x second averages in the end.