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.

67 lines
1.7 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. // czero is the process start time rounded down to the nearest clockRate
  13. // increment.
  14. var czero = time.Duration(time.Now().UnixNano()) / clockRate * clockRate
  15. // clock returns a low resolution timestamp relative to the process start time.
  16. func clock() time.Duration {
  17. return time.Duration(time.Now().UnixNano())/clockRate*clockRate - czero
  18. }
  19. // clockToTime converts a clock() timestamp to an absolute time.Time value.
  20. func clockToTime(c time.Duration) time.Time {
  21. return time.Unix(0, int64(czero+c))
  22. }
  23. // clockRound returns d rounded to the nearest clockRate increment.
  24. func clockRound(d time.Duration) time.Duration {
  25. return (d + clockRate>>1) / clockRate * clockRate
  26. }
  27. // round returns x rounded to the nearest int64 (non-negative values only).
  28. func round(x float64) int64 {
  29. if _, frac := math.Modf(x); frac >= 0.5 {
  30. return int64(math.Ceil(x))
  31. }
  32. return int64(math.Floor(x))
  33. }
  34. // Percent represents a percentage in increments of 1/1000th of a percent.
  35. type Percent uint32
  36. // percentOf calculates what percent of the total is x.
  37. func percentOf(x, total float64) Percent {
  38. if x < 0 || total <= 0 {
  39. return 0
  40. } else if p := round(x / total * 1e5); p <= math.MaxUint32 {
  41. return Percent(p)
  42. }
  43. return Percent(math.MaxUint32)
  44. }
  45. func (p Percent) Float() float64 {
  46. return float64(p) * 1e-3
  47. }
  48. func (p Percent) String() string {
  49. var buf [12]byte
  50. b := strconv.AppendUint(buf[:0], uint64(p)/1000, 10)
  51. n := len(b)
  52. b = strconv.AppendUint(b, 1000+uint64(p)%1000, 10)
  53. b[n] = '.'
  54. return string(append(b, '%'))
  55. }