Skip to content
This repository was archived by the owner on Aug 23, 2023. It is now read-only.

Commit 5dc80e5

Browse files
committed
we don't always need to regenerate keys
goos: linux goarch: amd64 pkg: github.com/grafana/metrictank/mdata/cache BenchmarkAddingManyChunksOneByOne-8 3000000 509 ns/op BenchmarkAddingManyChunksAtOnce-8 5000000 311 ns/op PASS ok github.com/grafana/metrictank/mdata/cache 9.482s
1 parent 9c6fb2f commit 5dc80e5

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

mdata/cache/ccache_metric.go

+35-4
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,8 @@ func (mc *CCacheMetric) AddRange(prev uint32, itergens []chunk.IterGen) {
9090
itergen := itergens[0]
9191
ts := itergen.Ts
9292

93+
addKeysDirect := len(mc.keys) == 0 || mc.keys[len(mc.keys)-1] < ts
94+
9395
// if previous chunk has not been passed we try to be smart and figure it out.
9496
// this is common in a scenario where a metric continuously gets queried
9597
// for a range that starts less than one chunkspan before now().
@@ -115,6 +117,9 @@ func (mc *CCacheMetric) AddRange(prev uint32, itergens []chunk.IterGen) {
115117
Next: itergens[1].Ts,
116118
Itgen: itergen,
117119
}
120+
if addKeysDirect {
121+
mc.keys = append(mc.keys, ts)
122+
}
118123
}
119124

120125
prev = ts
@@ -131,6 +136,9 @@ func (mc *CCacheMetric) AddRange(prev uint32, itergens []chunk.IterGen) {
131136
Next: itergens[i+1].Ts,
132137
Itgen: itergen,
133138
}
139+
if addKeysDirect {
140+
mc.keys = append(mc.keys, ts)
141+
}
134142
}
135143
prev = ts
136144
}
@@ -160,9 +168,15 @@ func (mc *CCacheMetric) AddRange(prev uint32, itergens []chunk.IterGen) {
160168
Next: next,
161169
Itgen: itergen,
162170
}
171+
if addKeysDirect {
172+
mc.keys = append(mc.keys, ts)
173+
}
174+
}
175+
176+
if !addKeysDirect {
177+
// regenerate the list of sorted keys
178+
mc.generateKeys()
163179
}
164-
// regenerate the list of sorted keys after adding a chunk
165-
mc.generateKeys()
166180

167181
return
168182
}
@@ -215,12 +229,29 @@ func (mc *CCacheMetric) Add(prev uint32, itergen chunk.IterGen) {
215229
}
216230
}
217231

218-
// regenerate the list of sorted keys after adding a chunk
219-
mc.generateKeys()
232+
mc.addKey(ts)
220233

221234
return
222235
}
223236

237+
func (mc *CCacheMetric) addKey(ts uint32) {
238+
239+
// if no keys yet, just add it and it's sorted
240+
if len(mc.keys) == 0 {
241+
mc.keys = append(mc.keys, ts)
242+
return
243+
}
244+
245+
// if ts is newer than any previous chunk, can just add to the back
246+
if mc.keys[len(mc.keys)-1] < ts {
247+
mc.keys = append(mc.keys, ts)
248+
return
249+
}
250+
251+
// we have to insert it in the middle, needs to be re-generated
252+
mc.generateKeys()
253+
}
254+
224255
// generateKeys generates sorted slice of all chunk timestamps
225256
// assumes we have at least read lock
226257
func (mc *CCacheMetric) generateKeys() {

0 commit comments

Comments
 (0)