feat: add histograms; fix possible bugs

mem-usage
Jef Roosens 2022-12-26 14:18:31 +01:00
parent d20e5c4553
commit 50be02f4a2
1 changed files with 46 additions and 15 deletions

View File

@ -7,51 +7,82 @@ struct CounterEntry {
index int
}
struct HistogramEntry {
metric Metric
pub mut:
data shared []f64
}
[heap]
struct DefaultMetricsCollector {
mut:
// The mutex for counters also applies to counter_indexes. Both data
// structuress are only ever updated together. Note that only registering a
// new metric actually changes these; all operations on already existing
// metrics use atomic operations on the elements of the counters array.
counters shared []u64
counter_indexes shared map[string]CounterEntry
counter_indexes map[string]CounterEntry
histograms shared map[string]HistogramEntry
}
pub fn new_default_metrics_collector() &DefaultMetricsCollector {
return &DefaultMetricsCollector{
counters: []u64{}
counter_indexes: map[string]CounterEntry{}
histograms: map[string]HistogramEntry{}
}
}
pub fn (mut c DefaultMetricsCollector) counter_register(value u64, metric Metric) {
new_index := lock c.counters {
lock c.counters {
c.counters << value
c.counters.len - 1
}
lock c.counter_indexes {
c.counter_indexes[metric.str()] = CounterEntry{
metric: metric
index: new_index
index: c.counters.len - 1
}
}
}
pub fn (mut c DefaultMetricsCollector) counter_increment(metric Metric) {
entry := rlock c.counter_indexes {
c.counter_indexes[metric.str()]
}
rlock c.counters {
entry := c.counter_indexes[metric.str()]
stdatomic.add_u64(&c.counters[entry.index], 1)
}
}
pub fn (mut c DefaultMetricsCollector) counter_decrement(metric Metric) {
entry := rlock c.counter_indexes {
c.counter_indexes[metric.str()]
}
rlock c.counters {
entry := c.counter_indexes[metric.str()]
stdatomic.sub_u64(&c.counters[entry.index], 1)
}
}
pub fn (mut c DefaultMetricsCollector) counter_get(metric Metric) ?u64 {
return rlock c.counters {
entry := c.counter_indexes[metric.str()] or { return none }
stdatomic.load_u64(&c.counters[entry.index])
}
}
pub fn (mut c DefaultMetricsCollector) histogram_register(metric Metric) {
lock c.histograms {
c.histograms[metric.str()] = HistogramEntry{
metric: metric
data: []f64{}
}
}
}
pub fn (mut c DefaultMetricsCollector) histogram_add(value f64, metric Metric) {
entry := rlock c.histograms {
c.histograms[metric.str()]
}
lock entry.data {
entry.data << value
}
}