github.com/searKing/golang/go@v1.2.117/time/duration.go (about)

     1  package time
     2  
     3  import (
     4  	"math/rand"
     5  	"time"
     6  )
     7  
     8  // InfDuration is the duration returned by Delay when a Reservation is not OK.
     9  const InfDuration = time.Duration(1<<63 - 1)
    10  
    11  // Jitter returns a time.Duration between
    12  // [duration - maxFactor*duration, duration + maxFactor*duration].
    13  //
    14  // This allows clients to avoid converging on periodic behavior.
    15  func Jitter(duration time.Duration, maxFactor float64) time.Duration {
    16  	delta := maxFactor * float64(duration)
    17  	minInterval := float64(duration) - delta
    18  	maxInterval := float64(duration) + delta
    19  	// Get a random value from the range [minInterval, maxInterval].
    20  	// The formula used below has a +1 because if the minInterval is 1 and the maxInterval is 3 then
    21  	// we want a 33% chance for selecting either 1, 2 or 3.
    22  	return time.Duration(minInterval + rand.Float64()*(maxInterval-minInterval+1))
    23  }