first commit
This commit is contained in:
+71
@@ -0,0 +1,71 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"backoff/fibonacci"
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func FormatOutput(pause time.Duration, ns bool) string {
|
||||
switch ns {
|
||||
case true:
|
||||
return strconv.FormatInt(pause.Nanoseconds(), 10)
|
||||
default:
|
||||
return pause.String()
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
start := time.Now()
|
||||
var (
|
||||
doPanic bool
|
||||
doSleep bool
|
||||
multiplier time.Duration
|
||||
jitter time.Duration
|
||||
iteration int64
|
||||
nanosecondsOutput bool
|
||||
)
|
||||
flag.BoolVar(&doPanic, "panic", false, "panic instead of overflowing values (default returns the max value instead of overflowing).")
|
||||
flag.BoolVar(&doSleep, "sleep", false, "sleep for the resulting duration after calculating it. prints the run duration of the program instead of the calculated pause duration.")
|
||||
flag.DurationVar(&multiplier, "multiplier", time.Millisecond, "pause multiplier.")
|
||||
flag.DurationVar(&jitter, "jitter", 0, "jitter boundary. pause duration is randomly selected in the range of resultDuration+-jitter.")
|
||||
flag.Int64Var(&iteration, "iteration", 1, "iteration to use for calculating pause time.")
|
||||
flag.BoolVar(&nanosecondsOutput, "ns", false, "outputs int64 nanoseconds instead of string.")
|
||||
flag.Parse()
|
||||
|
||||
if jitter < 0 {
|
||||
jitter = time.Duration(int(math.Abs(float64(jitter.Nanoseconds()))))
|
||||
}
|
||||
if iteration >= int64(len(fibonacci.TheFibonacciSequence)) {
|
||||
switch doPanic {
|
||||
case true:
|
||||
panic(fmt.Sprintf("error: input %d would overflow int64\n", iteration))
|
||||
default:
|
||||
maxIteration := int64(len(fibonacci.TheFibonacciSequence) - 1)
|
||||
fmt.Fprintf(os.Stderr, "iteration %d would overflow int64 - using %d\n", iteration, maxIteration)
|
||||
iteration = maxIteration
|
||||
}
|
||||
}
|
||||
|
||||
backoff := &fibonacci.FibonacciBackoff{
|
||||
Iteration: iteration,
|
||||
PauseMultiplier: multiplier,
|
||||
Jitter: jitter,
|
||||
}
|
||||
|
||||
var response string
|
||||
switch doSleep {
|
||||
case true:
|
||||
<-backoff.After(context.Background())
|
||||
response = FormatOutput(time.Since(start), nanosecondsOutput)
|
||||
default:
|
||||
response = FormatOutput(backoff.Next(), nanosecondsOutput)
|
||||
}
|
||||
fmt.Println(response)
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user