Merge branch 'collectd-5.4' into collectd-5.5
[collectd.git] / src / utils_latency.c
1 /**
2  * collectd - src/utils_latency.c
3  * Copyright (C) 2013       Florian Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian Forster <ff at octo.it>
25  **/
26
27 #include "collectd.h"
28 #include "plugin.h"
29 #include "utils_latency.h"
30 #include "common.h"
31
32 #include <math.h>
33 #include <limits.h>
34
35 #ifndef LLONG_MAX
36 # define LLONG_MAX 9223372036854775807LL
37 #endif
38
39 #ifndef HISTOGRAM_NUM_BINS
40 # define HISTOGRAM_NUM_BINS 1000
41 #endif
42
43 #ifndef HISTOGRAM_DEFAULT_BIN_WIDTH
44 /* 1048576 = 2^20 ^= 1/1024 s */
45 # define HISTOGRAM_DEFAULT_BIN_WIDTH 1048576
46 #endif
47
48 struct latency_counter_s
49 {
50   cdtime_t start_time;
51
52   cdtime_t sum;
53   size_t num;
54
55   cdtime_t min;
56   cdtime_t max;
57
58   cdtime_t bin_width;
59   int histogram[HISTOGRAM_NUM_BINS];
60 };
61
62 /*
63 * Histogram represents the distribution of data, it has a list of "bins".
64 * Each bin represents an interval and has a count (frequency) of
65 * number of values fall within its interval.
66 *
67 * Histogram's range is determined by the number of bins and the bin width,
68 * There are 1000 bins and all bins have the same width of default 1 millisecond.
69 * When a value above this range is added, Histogram's range is increased by
70 * increasing the bin width (note that number of bins remains always at 1000).
71 * This operation of increasing bin width is little expensive as each bin need
72 * to be visited to update it's count. To reduce frequent change of bin width,
73 * new bin width will be the next nearest power of 2. Example: 2, 4, 8, 16, 32,
74 * 64, 128, 256, 512, 1024, 2048, 5086, ...
75 *
76 * So, if the required bin width is 300, then new bin width will be 512 as it is
77 * the next nearest power of 2.
78 */
79 static void change_bin_width (latency_counter_t *lc, cdtime_t latency) /* {{{ */
80 {
81   /* This function is called because the new value is above histogram's range.
82    * First find the required bin width:
83    *           requiredBinWidth = (value + 1) / numBins
84    * then get the next nearest power of 2
85    *           newBinWidth = 2^(ceil(log2(requiredBinWidth)))
86    */
87   double required_bin_width = ((double) (latency + 1)) / ((double) HISTOGRAM_NUM_BINS);
88   double required_bin_width_logbase2 = log (required_bin_width) / log (2.0);
89   cdtime_t new_bin_width = (cdtime_t) (pow (2.0, ceil (required_bin_width_logbase2)) + .5);
90   cdtime_t old_bin_width = lc->bin_width;
91
92   lc->bin_width = new_bin_width;
93
94   /* bin_width has been increased, now iterate through all bins and move the
95    * old bin's count to new bin. */
96   if (lc->num > 0) // if the histogram has data then iterate else skip
97   {
98       double width_change_ratio = ((double) old_bin_width) / ((double) new_bin_width);
99       size_t i;
100
101       for (i = 0; i < HISTOGRAM_NUM_BINS; i++)
102       {
103          size_t new_bin = (size_t) (((double) i) * width_change_ratio);
104          if (i == new_bin)
105              continue;
106          assert (new_bin < i);
107
108          lc->histogram[new_bin] += lc->histogram[i];
109          lc->histogram[i] = 0;
110       }
111   }
112
113   DEBUG("utils_latency: change_bin_width: latency = %.3f; "
114       "old_bin_width = %.3f; new_bin_width = %.3f;",
115       CDTIME_T_TO_DOUBLE (latency),
116       CDTIME_T_TO_DOUBLE (old_bin_width),
117       CDTIME_T_TO_DOUBLE (new_bin_width));
118 } /* }}} void change_bin_width */
119
120 latency_counter_t *latency_counter_create (void) /* {{{ */
121 {
122   latency_counter_t *lc;
123
124   lc = malloc (sizeof (*lc));
125   if (lc == NULL)
126     return (NULL);
127   memset (lc, 0, sizeof (*lc));
128
129   latency_counter_reset (lc);
130   lc->bin_width = HISTOGRAM_DEFAULT_BIN_WIDTH;
131   return (lc);
132 } /* }}} latency_counter_t *latency_counter_create */
133
134 void latency_counter_destroy (latency_counter_t *lc) /* {{{ */
135 {
136   sfree (lc);
137 } /* }}} void latency_counter_destroy */
138
139 void latency_counter_add (latency_counter_t *lc, cdtime_t latency) /* {{{ */
140 {
141   cdtime_t bin;
142
143   if ((lc == NULL) || (latency == 0) || (latency > ((cdtime_t) LLONG_MAX)))
144     return;
145
146   lc->sum += latency;
147   lc->num++;
148
149   if ((lc->min == 0) && (lc->max == 0))
150     lc->min = lc->max = latency;
151   if (lc->min > latency)
152     lc->min = latency;
153   if (lc->max < latency)
154     lc->max = latency;
155
156   /* A latency of _exactly_ 1.0 ms should be stored in the buffer 0, so
157    * subtract one from the cdtime_t value so that exactly 1.0 ms get sorted
158    * accordingly. */
159   bin = (latency - 1) / lc->bin_width;
160   if (bin >= HISTOGRAM_NUM_BINS)
161   {
162       change_bin_width (lc, latency);
163       bin = (latency - 1) / lc->bin_width;
164       if (bin >= HISTOGRAM_NUM_BINS)
165       {
166           ERROR ("utils_latency: latency_counter_add: Invalid bin: %"PRIu64, bin);
167           return;
168       }
169   }
170   lc->histogram[bin]++;
171 } /* }}} void latency_counter_add */
172
173 void latency_counter_reset (latency_counter_t *lc) /* {{{ */
174 {
175   if (lc == NULL)
176     return;
177
178   cdtime_t bin_width = lc->bin_width;
179   memset (lc, 0, sizeof (*lc));
180
181   /* preserve bin width */
182   lc->bin_width = bin_width;
183   lc->start_time = cdtime ();
184 } /* }}} void latency_counter_reset */
185
186 cdtime_t latency_counter_get_min (latency_counter_t *lc) /* {{{ */
187 {
188   if (lc == NULL)
189     return (0);
190   return (lc->min);
191 } /* }}} cdtime_t latency_counter_get_min */
192
193 cdtime_t latency_counter_get_max (latency_counter_t *lc) /* {{{ */
194 {
195   if (lc == NULL)
196     return (0);
197   return (lc->max);
198 } /* }}} cdtime_t latency_counter_get_max */
199
200 cdtime_t latency_counter_get_sum (latency_counter_t *lc) /* {{{ */
201 {
202   if (lc == NULL)
203     return (0);
204   return (lc->sum);
205 } /* }}} cdtime_t latency_counter_get_sum */
206
207 size_t latency_counter_get_num (latency_counter_t *lc) /* {{{ */
208 {
209   if (lc == NULL)
210     return (0);
211   return (lc->num);
212 } /* }}} size_t latency_counter_get_num */
213
214 cdtime_t latency_counter_get_average (latency_counter_t *lc) /* {{{ */
215 {
216   double average;
217
218   if ((lc == NULL) || (lc->num == 0))
219     return (0);
220
221   average = CDTIME_T_TO_DOUBLE (lc->sum) / ((double) lc->num);
222   return (DOUBLE_TO_CDTIME_T (average));
223 } /* }}} cdtime_t latency_counter_get_average */
224
225 cdtime_t latency_counter_get_percentile (latency_counter_t *lc, /* {{{ */
226     double percent)
227 {
228   double percent_upper;
229   double percent_lower;
230   double p;
231   cdtime_t latency_lower;
232   cdtime_t latency_interpolated;
233   int sum;
234   size_t i;
235
236   if ((lc == NULL) || (lc->num == 0) || !((percent > 0.0) && (percent < 100.0)))
237     return (0);
238
239   /* Find index i so that at least "percent" events are within i+1 ms. */
240   percent_upper = 0.0;
241   percent_lower = 0.0;
242   sum = 0;
243   for (i = 0; i < HISTOGRAM_NUM_BINS; i++)
244   {
245     percent_lower = percent_upper;
246     sum += lc->histogram[i];
247     if (sum == 0)
248       percent_upper = 0.0;
249     else
250       percent_upper = 100.0 * ((double) sum) / ((double) lc->num);
251
252     if (percent_upper >= percent)
253       break;
254   }
255
256   if (i >= HISTOGRAM_NUM_BINS)
257     return (0);
258
259   assert (percent_upper >= percent);
260   assert (percent_lower < percent);
261
262   if (i == 0)
263     return (lc->bin_width);
264
265   latency_lower = ((cdtime_t) i) * lc->bin_width;
266   p = (percent - percent_lower) / (percent_upper - percent_lower);
267
268   latency_interpolated = latency_lower
269     + DOUBLE_TO_CDTIME_T (p * CDTIME_T_TO_DOUBLE (lc->bin_width));
270
271   DEBUG ("latency_counter_get_percentile: latency_interpolated = %.3f",
272       CDTIME_T_TO_DOUBLE (latency_interpolated));
273   return (latency_interpolated);
274 } /* }}} cdtime_t latency_counter_get_percentile */
275
276 /* vim: set sw=2 sts=2 et fdm=marker : */