@@ -16,12 +16,13 @@ package metrics
16
16
17
17
import (
18
18
"encoding/json"
19
+ "math"
19
20
"sort"
20
21
"time"
21
22
)
22
23
23
24
// RoundDuration is the default value used for rounding durations.
24
- var RoundDuration = time .Microsecond * 10
25
+ var RoundDuration = time .Millisecond * 1
25
26
26
27
type Calls map [string ]* CallStats
27
28
@@ -32,27 +33,39 @@ func (m Calls) MarshalJSON() ([]byte, error) {
32
33
calls = append (calls , s )
33
34
}
34
35
sort .Slice (calls , func (i , j int ) bool {
35
- return calls [i ].Total > calls [j ].Total
36
+ return calls [i ].Count > calls [j ].Count
36
37
})
38
+
39
+ /*var buf bytes.Buffer
40
+ buf.WriteByte('{')
41
+ for i, c := range calls {
42
+ if i > 0 {
43
+ buf.WriteByte(',')
44
+ }
45
+ buf.WriteString(fmt.Sprintf(`"%s":{"count":%d}`, c.Name, c.Count))
46
+ }
47
+ buf.WriteByte('}')
48
+ return buf.Bytes(), nil*/
49
+
37
50
return json .Marshal (calls )
38
51
}
39
52
40
53
// CallStats represents generic stats for call metrics.
41
54
type CallStats struct {
42
- Name string `json:",omitempty"`
43
- Count uint64
44
- Total Duration
45
- Avg Duration
46
- Min Duration
47
- Max Duration
55
+ Name string `json:"name ,omitempty"`
56
+ Count uint64 `json:"count"`
57
+ Total float64 `json:"total,omitempty"`
58
+ Avg float64 `json:"avg,omitempty"`
59
+ Min float64 `json:"min,omitempty"`
60
+ Max float64 `json:"max,omitempty"`
48
61
}
49
62
50
63
// Increment increments call count and recalculates durations
51
64
func (m * CallStats ) Increment (d time.Duration ) {
52
- took := Duration ( d )
65
+ took := d . Round ( RoundDuration ). Seconds ( )
53
66
m .Count ++
54
- m .Total += took
55
- m .Avg = m .Total / Duration (m .Count )
67
+ m .Total = round ( m . Total + took )
68
+ m .Avg = round ( m .Total / float64 (m .Count ) )
56
69
if took > m .Max {
57
70
m .Max = took
58
71
}
@@ -61,23 +74,17 @@ func (m *CallStats) Increment(d time.Duration) {
61
74
}
62
75
}
63
76
64
- /*
77
+ func round (n float64 ) float64 {
78
+ return math .Round (n * 1000 ) / 1000
79
+ }
80
+
65
81
// MarshalJSON implements json.Marshaler interface
66
- func (m *CallStats) MarshalJSON() ([]byte, error) {
82
+ /* func (m *CallStats) MarshalJSON() ([]byte, error) {
67
83
var d string
68
84
d = fmt.Sprintf(
69
- "count: %d, total: %s (avg/min/max: %s/%s/%s)",
70
- m.Count, durStr(m.TotalDur ),
71
- durStr(m.AvgDur ), durStr(m.MinDur ), durStr(m.MaxDur ),
85
+ "%s - count: %d, total: %s (avg/min/max: %s/%s/%s)",
86
+ m.Name, m. Count, durStr(m.Total ),
87
+ durStr(m.Avg ), durStr(m.Min ), durStr(m.Max ),
72
88
)
73
89
return json.Marshal(d)
74
- }
75
- */
76
-
77
- type Duration time.Duration
78
-
79
- // MarshalJSON implements json.Marshaler interface
80
- func (m * Duration ) MarshalJSON () ([]byte , error ) {
81
- s := time .Duration (* m ).Round (RoundDuration ).String ()
82
- return json .Marshal (s )
83
- }
90
+ }*/
0 commit comments