github.com/vipernet-xyz/tm@v0.34.24/libs/flowrate/util.go (about)

     1  //
     2  // Written by Maxim Khitrov (November 2012)
     3  //
     4  
     5  package flowrate
     6  
     7  import (
     8  	"math"
     9  	"strconv"
    10  	"time"
    11  )
    12  
    13  // clockRate is the resolution and precision of clock().
    14  const clockRate = 20 * time.Millisecond
    15  
    16  // czero is the process start time rounded down to the nearest clockRate
    17  // increment.
    18  var czero = time.Now().Round(clockRate)
    19  
    20  // clock returns a low resolution timestamp relative to the process start time.
    21  func clock() time.Duration {
    22  	return time.Now().Round(clockRate).Sub(czero)
    23  }
    24  
    25  // clockToTime converts a clock() timestamp to an absolute time.Time value.
    26  func clockToTime(c time.Duration) time.Time {
    27  	return czero.Add(c)
    28  }
    29  
    30  // clockRound returns d rounded to the nearest clockRate increment.
    31  func clockRound(d time.Duration) time.Duration {
    32  	return (d + clockRate>>1) / clockRate * clockRate
    33  }
    34  
    35  // round returns x rounded to the nearest int64 (non-negative values only).
    36  func round(x float64) int64 {
    37  	if _, frac := math.Modf(x); frac >= 0.5 {
    38  		return int64(math.Ceil(x))
    39  	}
    40  	return int64(math.Floor(x))
    41  }
    42  
    43  // Percent represents a percentage in increments of 1/1000th of a percent.
    44  type Percent uint32
    45  
    46  // percentOf calculates what percent of the total is x.
    47  func percentOf(x, total float64) Percent {
    48  	if x < 0 || total <= 0 {
    49  		return 0
    50  	} else if p := round(x / total * 1e5); p <= math.MaxUint32 {
    51  		return Percent(p)
    52  	}
    53  	return Percent(math.MaxUint32)
    54  }
    55  
    56  func (p Percent) Float() float64 {
    57  	return float64(p) * 1e-3
    58  }
    59  
    60  func (p Percent) String() string {
    61  	var buf [12]byte
    62  	b := strconv.AppendUint(buf[:0], uint64(p)/1000, 10)
    63  	n := len(b)
    64  	b = strconv.AppendUint(b, 1000+uint64(p)%1000, 10)
    65  	b[n] = '.'
    66  	return string(append(b, '%'))
    67  }