Skip to content

Instantly share code, notes, and snippets.

@usahg
Created January 19, 2012 13:23
Show Gist options
  • Save usahg/1640033 to your computer and use it in GitHub Desktop.
Save usahg/1640033 to your computer and use it in GitHub Desktop.
ruby implementation of exponential back off algorithm
# EC = 1/2*(2**exp-1)
# ^equation
def exp_backoff(upto)
result = [ ]
# ^ stores wait periods
(1..upto).each do |iter|
result << (1.0/2.0*(2.0**iter - 1.0)).ceil
# using ceil to round off
end
return result
end
# print a list containing wait durations
# these wait durations are in exponential increasing order
# exponential back off algorithm is used in networking hardware to augment successive waiting periods following failed connect attempts
# this implementation is for w3c validator script repo, even though 1 second wait period is enough while querying w3c api
# this is just for fun
puts exp_backoff(9)
# get waiting for periods for 9 tries
puts exp_backoff(3)[2]
# get the last and longest waiting period for three tries
@brewboy
Copy link

brewboy commented Apr 28, 2014

How about:

result << (2**iter)/2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment