From 6e6a6a0eff7fd8e6113374283b7d1ec1737dcca4 Mon Sep 17 00:00:00 2001 From: Tiffany Wang Date: Sat, 13 Nov 2021 21:13:50 -0800 Subject: [PATCH] exponential backoff algorithm should not truncate exponential factor --- backoff/backoff.go | 2 +- backoff/backoff_test.go | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/backoff/backoff.go b/backoff/backoff.go index 43ac4a8..e159b27 100644 --- a/backoff/backoff.go +++ b/backoff/backoff.go @@ -34,7 +34,7 @@ func Linear(factor time.Duration) Algorithm { // calculated as the given base raised to the attempt number. func Exponential(factor time.Duration, base float64) Algorithm { return func(attempt uint) time.Duration { - return (factor * time.Duration(math.Pow(base, float64(attempt)))) + return time.Duration(float64(factor) * math.Pow(base, float64(attempt))) } } diff --git a/backoff/backoff_test.go b/backoff/backoff_test.go index c5a2e36..ea7e871 100644 --- a/backoff/backoff_test.go +++ b/backoff/backoff_test.go @@ -40,13 +40,13 @@ func TestLinear(t *testing.T) { func TestExponential(t *testing.T) { const duration = time.Second - const base = 3 + const base = 1.5 algorithm := Exponential(duration, base) for i := uint(0); i < 10; i++ { result := algorithm(i) - expected := time.Duration(math.Pow(base, float64(i))) * duration + expected := time.Duration(math.Pow(base, float64(i)) * float64(duration)) if result != expected { t.Errorf("algorithm expected to return a %s duration, but received %s instead", expected, result) @@ -132,7 +132,7 @@ func ExampleLinear() { } func ExampleExponential() { - algorithm := Exponential(15*time.Millisecond, 3) + algorithm := Exponential(15*time.Millisecond, 1.5) for i := uint(1); i <= 5; i++ { duration := algorithm(i) @@ -141,11 +141,11 @@ func ExampleExponential() { } // Output: - // #1 attempt: 45ms - // #2 attempt: 135ms - // #3 attempt: 405ms - // #4 attempt: 1.215s - // #5 attempt: 3.645s + // #1 attempt: 22.5ms + // #2 attempt: 33.75ms + // #3 attempt: 50.625ms + // #4 attempt: 75.9375ms + // #5 attempt: 113.90625ms } func ExampleBinaryExponential() {