2 // Written by Maxim Khitrov (November 2012)
13 // clockRate is the resolution and precision of clock().
14 const clockRate = 20 * time.Millisecond
16 // czero is the process start time rounded down to the nearest clockRate
18 var czero = time.Now().Round(clockRate)
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)
25 // clockToTime converts a clock() timestamp to an absolute time.Time value.
26 func clockToTime(c time.Duration) time.Time {
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
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))
40 return int64(math.Floor(x))
43 // Percent represents a percentage in increments of 1/1000th of a percent.
46 // percentOf calculates what percent of the total is x.
47 func percentOf(x, total float64) Percent {
48 if x < 0 || total <= 0 {
50 } else if p := round(x / total * 1e5); p <= math.MaxUint32 {
53 return Percent(math.MaxUint32)
56 func (p Percent) Float() float64 {
57 return float64(p) * 1e-3
60 func (p Percent) String() string {
62 b := strconv.AppendUint(buf[:0], uint64(p)/1000, 10)
64 b = strconv.AppendUint(b, 1000+uint64(p)%1000, 10)
66 return string(append(b, '%'))