...
1
2
3
4
5 package flowrate
6
7 import (
8 "math"
9 "strconv"
10 "time"
11 )
12
13
14 const clockRate = 20 * time.Millisecond
15
16
17
18 var czero = time.Duration(time.Now().UnixNano()) / clockRate * clockRate
19
20
21 func clock() time.Duration {
22 return time.Duration(time.Now().UnixNano())/clockRate*clockRate - czero
23 }
24
25
26 func clockToTime(c time.Duration) time.Time {
27 return time.Unix(0, int64(czero+c))
28 }
29
30
31 func clockRound(d time.Duration) time.Duration {
32 return (d + clockRate>>1) / clockRate * clockRate
33 }
34
35
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
44 type Percent uint32
45
46
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 }
68
View as plain text