This repository has been archived by the owner on Jun 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortmemory.go
117 lines (103 loc) · 2.36 KB
/
shortmemory.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"errors"
"time"
)
const (
memoryLength = 10
)
var (
memory map[string]*TimeseriesMeasures = make(map[string]*TimeseriesMeasures)
)
type Measure struct {
Older *Measure
Later *Measure
Timestamp time.Time
Value float64
}
// TimeSeriesMeasures is a linked list holding measures.
type TimeseriesMeasures struct {
Oldest *Measure
Latest *Measure
}
func (m *TimeseriesMeasures) Add(measure *Measure) {
if m.Length() >= memoryLength {
oldest := m.Oldest
m.Oldest = oldest.Later
oldest = nil
}
latest := m.Latest
latest.Later = measure
m.Latest = measure
}
func (m *TimeseriesMeasures) Get() (time.Time, float64) {
return m.Latest.Timestamp, m.Latest.Value
}
func (m *TimeseriesMeasures) Length() (length int32) {
measure := m.Oldest
for {
length += 1
if measure.Later == nil {
break
}
measure = measure.Later
}
return
}
func (m *TimeseriesMeasures) Print() []float64 {
var result []float64
var measure *Measure = m.Oldest
for {
result = append(result, measure.Value)
if measure.Later == nil {
break
}
measure = measure.Later
}
return result
}
func CreateTimeseriesMeasure(measure *Measure) *TimeseriesMeasures {
timeseriesMeasure := TimeseriesMeasures{}
timeseriesMeasure.Oldest = measure
timeseriesMeasure.Latest = measure
return ×eriesMeasure
}
// Sum adds up the values stored in the topic
func (m *TimeseriesMeasures) Sum() (sum float64) {
measure := m.Oldest
for {
sum += measure.Value
if measure.Later == nil {
break
}
measure = measure.Later
}
return
}
// Avg averages the values stored in the topic
func (m *TimeseriesMeasures) Avg() float64 {
return m.Sum() / float64(m.Length())
}
// AddMeasure takes topic, timestamp, and value and stores them
// in a time series database. Timestamp is a nano-second precision epoch value.
func AddMeasure(topic string, timestampNs int64, value float64) {
if _, ok := memory[topic]; !ok {
memory[topic] = CreateTimeseriesMeasure(&Measure{
Timestamp: time.Unix(0, timestampNs),
Value: value,
})
} else {
timeSeriesMeasures := memory[topic]
timeSeriesMeasures.Add(&Measure{
Timestamp: time.Unix(0, timestampNs),
Value: value,
})
}
}
func GetTopic(topic string) (*TimeseriesMeasures, error) {
if _, ok := memory[topic]; ok {
return memory[topic], nil
} else {
return nil, errors.New("No such topic exists")
}
}