]> git.sesse.net Git - nageru/blob - metrics.h
Add a histogram of output crf values from x264.
[nageru] / metrics.h
1 #ifndef _METRICS_H
2 #define _METRICS_H 1
3
4 // A simple global class to keep track of metrics export in Prometheus format.
5 // It would be better to use a more full-featured Prometheus client library for this,
6 // but it would introduce a dependency that is not commonly packaged in distributions,
7 // which makes it quite unwieldy. Thus, we'll package our own for the time being.
8
9 #include <atomic>
10 #include <mutex>
11 #include <string>
12 #include <map>
13 #include <vector>
14
15 class Metrics {
16 public:
17         enum Type {
18                 TYPE_COUNTER,
19                 TYPE_GAUGE,
20         };
21
22         void add(const std::string &name, std::atomic<int64_t> *location, Type type = TYPE_COUNTER)
23         {
24                 add(name, {}, location, type);
25         }
26
27         void add(const std::string &name, std::atomic<double> *location, Type type = TYPE_COUNTER)
28         {
29                 add(name, {}, location, type);
30         }
31
32         void add(const std::string &name, const std::vector<std::pair<std::string, std::string>> &labels, std::atomic<int64_t> *location, Type type = TYPE_COUNTER);
33         void add(const std::string &name, const std::vector<std::pair<std::string, std::string>> &labels, std::atomic<double> *location, Type type = TYPE_COUNTER);
34
35         // Only integer histogram, ie. keys are 0..(N-1).
36         void add_histogram(const std::string &name, const std::vector<std::pair<std::string, std::string>> &labels, std::atomic<int64_t> *first_bucket_location, std::atomic<double> *sum_location, size_t num_elements);
37
38         std::string serialize() const;
39
40 private:
41         enum DataType {
42                 DATA_TYPE_INT64,
43                 DATA_TYPE_DOUBLE,
44         };
45
46         struct Metric {
47                 DataType data_type;
48                 std::string name;
49                 std::vector<std::pair<std::string, std::string>> labels;
50                 union {
51                         std::atomic<int64_t> *location_int64;
52                         std::atomic<double> *location_double;
53                 };
54         };
55
56         // TODO: This needs to be more general.
57         struct Histogram {
58                 std::string name;
59                 std::vector<std::pair<std::string, std::string>> labels;
60                 std::atomic<int64_t> *first_bucket_location;
61                 std::atomic<double> *sum_location;
62                 size_t num_elements;
63         };
64
65         mutable std::mutex mu;
66         std::map<std::string, Type> types;
67         std::vector<Metric> metrics;
68         std::vector<Histogram> histograms;
69 };
70
71 extern Metrics global_metrics;
72
73 #endif  // !defined(_METRICS_H)