You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.4 KiB

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