1
2
3
4
5 package metrics_test
6
7 import (
8 "fmt"
9 "runtime/metrics"
10 )
11
12 func ExampleRead_readingOneMetric() {
13
14 const myMetric = "/memory/classes/heap/free:bytes"
15
16
17 sample := make([]metrics.Sample, 1)
18 sample[0].Name = myMetric
19
20
21 metrics.Read(sample)
22
23
24
25
26 if sample[0].Value.Kind() == metrics.KindBad {
27 panic(fmt.Sprintf("metric %q no longer supported", myMetric))
28 }
29
30
31
32
33
34 freeBytes := sample[0].Value.Uint64()
35
36 fmt.Printf("free but not released memory: %d\n", freeBytes)
37 }
38
39 func ExampleRead_readingAllMetrics() {
40
41 descs := metrics.All()
42
43
44 samples := make([]metrics.Sample, len(descs))
45 for i := range samples {
46 samples[i].Name = descs[i].Name
47 }
48
49
50 metrics.Read(samples)
51
52
53 for _, sample := range samples {
54
55 name, value := sample.Name, sample.Value
56
57
58 switch value.Kind() {
59 case metrics.KindUint64:
60 fmt.Printf("%s: %d\n", name, value.Uint64())
61 case metrics.KindFloat64:
62 fmt.Printf("%s: %f\n", name, value.Float64())
63 case metrics.KindFloat64Histogram:
64
65
66 fmt.Printf("%s: %f\n", name, medianBucket(value.Float64Histogram()))
67 case metrics.KindBad:
68
69
70 panic("bug in runtime/metrics package!")
71 default:
72
73
74
75
76
77 fmt.Printf("%s: unexpected metric Kind: %v\n", name, value.Kind())
78 }
79 }
80 }
81
82 func medianBucket(h *metrics.Float64Histogram) float64 {
83 total := uint64(0)
84 for _, count := range h.Counts {
85 total += count
86 }
87 thresh := total / 2
88 total = 0
89 for i, count := range h.Counts {
90 total += count
91 if total >= thresh {
92 return h.Buckets[i]
93 }
94 }
95 panic("should not happen")
96 }
97
View as plain text