2 * Copyright 2014 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #ifndef FOLLY_STATS_BUCKETEDTIMESERIES_H_
18 #define FOLLY_STATS_BUCKETEDTIMESERIES_H_
23 #include "folly/detail/Stats.h"
28 * This class represents a bucketed time series which keeps track of values
29 * added in the recent past, and merges these values together into a fixed
30 * number of buckets to keep a lid on memory use if the number of values
31 * added is very large.
33 * For example, a BucketedTimeSeries() with duration == 60s and 10 buckets
34 * will keep track of 10 6-second buckets, and discard all data added more
35 * than 1 minute ago. As time ticks by, a 6-second bucket at a time will
36 * be discarded and new data will go into the newly opened bucket. Internally,
37 * it uses a circular array of buckets that it reuses as time advances.
39 * The class assumes that time advances forward -- you can't retroactively add
40 * values for events in the past -- the 'now' argument is provided for better
41 * efficiency and ease of unittesting.
44 * This class is not thread-safe -- use your own synchronization!
46 template <typename VT, typename TT=std::chrono::seconds>
47 class BucketedTimeSeries {
51 typedef detail::Bucket<ValueType> Bucket;
54 * Create a new BucketedTimeSeries.
56 * This creates a new BucketedTimeSeries with the specified number of
57 * buckets, storing data for the specified amount of time.
59 * If the duration is 0, the BucketedTimeSeries will track data forever,
60 * and does not need the rolling buckets. The numBuckets parameter is
61 * ignored when duration is 0.
63 BucketedTimeSeries(size_t numBuckets, TimeType duration);
66 * Adds the value 'val' at time 'now'
68 * This function expects time to always move forwards: it cannot be used to
69 * add historical data points that have occurred in the past. If now is
70 * older than the another timestamp that has already been passed to
71 * addValue() or update(), now will be ignored and the latest timestamp will
74 void addValue(TimeType now, const ValueType& val);
77 * Adds the value 'val' the given number of 'times' at time 'now'
79 void addValue(TimeType now, const ValueType& val, int64_t times);
82 * Adds the value 'sum' as the sum of 'nsamples' samples
84 void addValueAggregated(TimeType now, const ValueType& sum, int64_t nsamples);
87 * Updates the container to the specified time, doing all the necessary
88 * work to rotate the buckets and remove any stale data points.
90 * The addValue() methods automatically call update() when adding new data
91 * points. However, when reading data from the timeseries, you should make
92 * sure to manually call update() before accessing the data. Otherwise you
93 * may be reading stale data if update() has not been called recently.
95 * Returns the current bucket index after the update.
97 size_t update(TimeType now);
100 * Reset the timeseries to an empty state,
101 * as if no data points have ever been added to it.
106 * Get the latest time that has ever been passed to update() or addValue().
108 * If no data has ever been added to this timeseries, 0 will be returned.
110 TimeType getLatestTime() const {
115 * Get the time of the earliest data point stored in this timeseries.
117 * If no data has ever been added to this timeseries, 0 will be returned.
119 * If isAllTime() is true, this is simply the time when the first data point
122 * For non-all-time data, the timestamp reflects the first data point still
123 * remembered. As new data points are added, old data will be expired.
124 * getEarliestTime() returns the timestamp of the oldest bucket still present
125 * in the timeseries. This will never be older than (getLatestTime() -
128 TimeType getEarliestTime() const;
131 * Return the number of buckets.
133 size_t numBuckets() const {
134 return buckets_.size();
138 * Return the maximum duration of data that can be tracked by this
139 * BucketedTimeSeries.
141 TimeType duration() const {
146 * Returns true if this BucketedTimeSeries stores data for all-time, without
147 * ever rolling over into new buckets.
149 bool isAllTime() const {
150 return (duration_ == TimeType(0));
154 * Returns true if no calls to update() have been made since the last call to
158 // We set firstTime_ greater than latestTime_ in the constructor and in
159 // clear, so we use this to distinguish if the timeseries is empty.
161 // Once a data point has been added, latestTime_ will always be greater
162 // than or equal to firstTime_.
163 return firstTime_ > latestTime_;
167 * Get the amount of time tracked by this timeseries.
169 * For an all-time timeseries, this returns the length of time since the
170 * first data point was added to the time series.
172 * Otherwise, this never returns a value greater than the overall timeseries
173 * duration. If the first data point was recorded less than a full duration
174 * ago, the time since the first data point is returned. If a full duration
175 * has elapsed, and we have already thrown away some data, the time since the
176 * oldest bucket is returned.
178 * For example, say we are tracking 600 seconds worth of data, in 60 buckets.
179 * - If less than 600 seconds have elapsed since the first data point,
180 * elapsed() returns the total elapsed time so far.
181 * - If more than 600 seconds have elapsed, we have already thrown away some
182 * data. However, we throw away a full bucket (10 seconds worth) at once,
183 * so at any point in time we have from 590 to 600 seconds worth of data.
184 * elapsed() will therefore return a value between 590 and 600.
186 * Note that you generally should call update() before calling elapsed(), to
187 * make sure you are not reading stale data.
189 TimeType elapsed() const;
192 * Get the amount of time tracked by this timeseries, between the specified
193 * start and end times.
195 * If the timeseries contains data for the entire time range specified, this
196 * simply returns (end - start). However, if start is earlier than
197 * getEarliestTime(), this returns (end - getEarliestTime()).
199 TimeType elapsed(TimeType start, TimeType end) const;
202 * Return the sum of all the data points currently tracked by this
203 * BucketedTimeSeries.
205 * Note that you generally should call update() before calling sum(), to
206 * make sure you are not reading stale data.
208 const ValueType& sum() const {
213 * Return the number of data points currently tracked by this
214 * BucketedTimeSeries.
216 * Note that you generally should call update() before calling count(), to
217 * make sure you are not reading stale data.
219 uint64_t count() const {
224 * Return the average value (sum / count).
226 * The return type may be specified to control whether floating-point or
227 * integer division should be performed.
229 * Note that you generally should call update() before calling avg(), to
230 * make sure you are not reading stale data.
232 template <typename ReturnType=double>
233 ReturnType avg() const {
234 return total_.template avg<ReturnType>();
238 * Return the sum divided by the elapsed time.
240 * Note that you generally should call update() before calling rate(), to
241 * make sure you are not reading stale data.
243 template <typename ReturnType=double, typename Interval=TimeType>
244 ReturnType rate() const {
245 return rateHelper<ReturnType, Interval>(total_.sum, elapsed());
249 * Return the count divided by the elapsed time.
251 * The Interval template parameter causes the elapsed time to be converted to
252 * the Interval type before using it. For example, if Interval is
253 * std::chrono::seconds, the return value will be the count per second.
254 * If Interval is std::chrono::hours, the return value will be the count per
257 * Note that you generally should call update() before calling countRate(),
258 * to make sure you are not reading stale data.
260 template <typename ReturnType=double, typename Interval=TimeType>
261 ReturnType countRate() const {
262 return rateHelper<ReturnType, Interval>(total_.count, elapsed());
266 * Estimate the sum of the data points that occurred in the specified time
269 * The range queried is [start, end).
270 * That is, start is inclusive, and end is exclusive.
272 * Note that data outside of the timeseries duration will no longer be
273 * available for use in the estimation. Specifying a start time earlier than
274 * getEarliestTime() will not have much effect, since only data points after
275 * that point in time will be counted.
277 * Note that the value returned is an estimate, and may not be precise.
279 ValueType sum(TimeType start, TimeType end) const;
282 * Estimate the number of data points that occurred in the specified time
285 * The same caveats documented in the sum(TimeType start, TimeType end)
286 * comments apply here as well.
288 uint64_t count(TimeType start, TimeType end) const;
291 * Estimate the average value during the specified time period.
293 * The same caveats documented in the sum(TimeType start, TimeType end)
294 * comments apply here as well.
296 template <typename ReturnType=double>
297 ReturnType avg(TimeType start, TimeType end) const;
300 * Estimate the rate during the specified time period.
302 * The same caveats documented in the sum(TimeType start, TimeType end)
303 * comments apply here as well.
305 template <typename ReturnType=double, typename Interval=TimeType>
306 ReturnType rate(TimeType start, TimeType end) const {
307 ValueType intervalSum = sum(start, end);
308 TimeType interval = elapsed(start, end);
309 return rateHelper<ReturnType, Interval>(intervalSum, interval);
313 * Estimate the rate of data points being added during the specified time
316 * The same caveats documented in the sum(TimeType start, TimeType end)
317 * comments apply here as well.
319 template <typename ReturnType=double, typename Interval=TimeType>
320 ReturnType countRate(TimeType start, TimeType end) const {
321 uint64_t intervalCount = count(start, end);
322 TimeType interval = elapsed(start, end);
323 return rateHelper<ReturnType, Interval>(intervalCount, interval);
327 * Invoke a function for each bucket.
329 * The function will take as arguments the bucket index,
330 * the bucket start time, and the start time of the subsequent bucket.
332 * It should return true to continue iterating through the buckets, and false
333 * to break out of the loop and stop, without calling the function on any
336 * bool function(const Bucket& bucket, TimeType bucketStart,
337 * TimeType nextBucketStart)
339 template <typename Function>
340 void forEachBucket(Function fn) const;
343 * Get the index for the bucket containing the specified time.
345 * Note that the index is only valid if this time actually falls within one
346 * of the current buckets. If you pass in a value more recent than
347 * getLatestTime() or older than (getLatestTime() - elapsed()), the index
348 * returned will not be valid.
350 * This method may not be called for all-time data.
352 size_t getBucketIdx(TimeType time) const;
355 * Get the bucket at the specified index.
357 * This method may not be called for all-time data.
359 const Bucket& getBucketByIndex(size_t idx) const {
360 return buckets_[idx];
364 * Compute the bucket index that the specified time falls into,
365 * as well as the bucket start time and the next bucket's start time.
367 * This method may not be called for all-time data.
369 void getBucketInfo(TimeType time, size_t* bucketIdx,
370 TimeType* bucketStart, TimeType* nextBucketStart) const;
373 template <typename ReturnType=double, typename Interval=TimeType>
374 ReturnType rateHelper(ReturnType numerator, TimeType elapsed) const {
375 return detail::rateHelper<ReturnType, TimeType, Interval>(numerator,
379 ValueType rangeAdjust(TimeType bucketStart, TimeType nextBucketStart,
380 TimeType start, TimeType end,
381 ValueType input) const;
383 template <typename Function>
384 void forEachBucket(TimeType start, TimeType end, Function fn) const;
386 TimeType firstTime_; // time of first update() since clear()/constructor
387 TimeType latestTime_; // time of last update()
388 TimeType duration_; // total duration ("window length") of the time series
390 Bucket total_; // sum and count of everything in time series
391 std::vector<Bucket> buckets_; // actual buckets of values
396 #endif // FOLLY_STATS_BUCKETEDTIMESERIES_H_