2 * Copyright 2017 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.
22 #include <folly/detail/Stats.h>
27 * A helper clock type to helper older code using BucketedTimeSeries with
28 * std::chrono::seconds transition to properly using clock types and time_point
31 template <typename TT = std::chrono::seconds>
32 class LegacyStatsClock {
35 using time_point = std::chrono::time_point<LegacyStatsClock, TT>;
37 // This clock does not actually implement now(), since the older API
38 // did not really specify what clock should be used. (In practice most
39 // callers unfortuantely used wall clock time rather than a monotonic clock.)
43 * This class represents a bucketed time series which keeps track of values
44 * added in the recent past, and merges these values together into a fixed
45 * number of buckets to keep a lid on memory use if the number of values
46 * added is very large.
48 * For example, a BucketedTimeSeries() with duration == 60s and 10 buckets
49 * will keep track of 10 6-second buckets, and discard all data added more
50 * than 1 minute ago. As time ticks by, a 6-second bucket at a time will
51 * be discarded and new data will go into the newly opened bucket. Internally,
52 * it uses a circular array of buckets that it reuses as time advances.
54 * This class assumes that time advances forwards. The window of time tracked
55 * by the timeseries will advance forwards whenever a more recent timestamp is
56 * passed to addValue(). While it is possible to pass old time values to
57 * addValue(), this will never move the time window backwards. If the old time
58 * value falls outside the tracked window of time, the data point will be
61 * This class is not thread-safe -- use your own synchronization!
63 template <typename VT, typename CT = LegacyStatsClock<std::chrono::seconds>>
64 class BucketedTimeSeries {
68 using Duration = typename Clock::duration;
69 using TimePoint = typename Clock::time_point;
70 using Bucket = detail::Bucket<ValueType>;
73 * Create a new BucketedTimeSeries.
75 * This creates a new BucketedTimeSeries with the specified number of
76 * buckets, storing data for the specified amount of time.
78 * If the duration is 0, the BucketedTimeSeries will track data forever,
79 * and does not need the rolling buckets. The numBuckets parameter is
80 * ignored when duration is 0.
82 BucketedTimeSeries(size_t numBuckets, Duration duration);
85 * Adds the value 'val' at time 'now'
87 * This function expects time to generally move forwards. The window of time
88 * tracked by this time series will move forwards with time. If 'now' is
89 * more recent than any time previously seen, addValue() will automatically
90 * call update(now) to advance the time window tracked by this data
93 * Values in the recent past may be added to the data structure by passing in
94 * a slightly older value of 'now', as long as this time point still falls
95 * within the tracked duration. If 'now' is older than the tracked duration
96 * of time, the data point value will be ignored, and addValue() will return
97 * false without doing anything else.
99 * Returns true on success, or false if now was older than the tracked time
102 bool addValue(TimePoint now, const ValueType& val);
105 * Adds the value 'val' the given number of 'times' at time 'now'
107 bool addValue(TimePoint now, const ValueType& val, uint64_t times);
110 * Adds the value 'total' as the sum of 'nsamples' samples
113 addValueAggregated(TimePoint now, const ValueType& total, uint64_t nsamples);
116 * Updates the container to the specified time, doing all the necessary
117 * work to rotate the buckets and remove any stale data points.
119 * The addValue() methods automatically call update() when adding new data
120 * points. However, when reading data from the timeseries, you should make
121 * sure to manually call update() before accessing the data. Otherwise you
122 * may be reading stale data if update() has not been called recently.
124 * Returns the current bucket index after the update.
126 size_t update(TimePoint now);
129 * Reset the timeseries to an empty state,
130 * as if no data points have ever been added to it.
135 * Get the latest time that has ever been passed to update() or addValue().
137 * If no data has ever been added to this timeseries, 0 will be returned.
139 TimePoint getLatestTime() const {
144 * Get the time of the earliest data point stored in this timeseries.
146 * If no data has ever been added to this timeseries, 0 will be returned.
148 * If isAllTime() is true, this is simply the time when the first data point
151 * For non-all-time data, the timestamp reflects the first data point still
152 * remembered. As new data points are added, old data will be expired.
153 * getEarliestTime() returns the timestamp of the oldest bucket still present
154 * in the timeseries. This will never be older than (getLatestTime() -
157 TimePoint getEarliestTime() const;
160 * Return the number of buckets.
162 size_t numBuckets() const {
163 return buckets_.size();
167 * Return the maximum duration of data that can be tracked by this
168 * BucketedTimeSeries.
170 Duration duration() const {
175 * Returns true if this BucketedTimeSeries stores data for all-time, without
176 * ever rolling over into new buckets.
178 bool isAllTime() const {
179 return (duration_ == Duration(0));
183 * Returns true if no calls to update() have been made since the last call to
187 // We set firstTime_ greater than latestTime_ in the constructor and in
188 // clear, so we use this to distinguish if the timeseries is empty.
190 // Once a data point has been added, latestTime_ will always be greater
191 // than or equal to firstTime_.
192 return firstTime_ > latestTime_;
196 * Get the amount of time tracked by this timeseries.
198 * For an all-time timeseries, this returns the length of time since the
199 * first data point was added to the time series.
201 * Otherwise, this never returns a value greater than the overall timeseries
202 * duration. If the first data point was recorded less than a full duration
203 * ago, the time since the first data point is returned. If a full duration
204 * has elapsed, and we have already thrown away some data, the time since the
205 * oldest bucket is returned.
207 * For example, say we are tracking 600 seconds worth of data, in 60 buckets.
208 * - If less than 600 seconds have elapsed since the first data point,
209 * elapsed() returns the total elapsed time so far.
210 * - If more than 600 seconds have elapsed, we have already thrown away some
211 * data. However, we throw away a full bucket (10 seconds worth) at once,
212 * so at any point in time we have from 590 to 600 seconds worth of data.
213 * elapsed() will therefore return a value between 590 and 600.
215 * Note that you generally should call update() before calling elapsed(), to
216 * make sure you are not reading stale data.
218 Duration elapsed() const;
221 * Get the amount of time tracked by this timeseries, between the specified
222 * start and end times.
224 * If the timeseries contains data for the entire time range specified, this
225 * simply returns (end - start). However, if start is earlier than
226 * getEarliestTime(), this returns (end - getEarliestTime()).
228 Duration elapsed(TimePoint start, TimePoint end) const;
231 * Return the sum of all the data points currently tracked by this
232 * BucketedTimeSeries.
234 * Note that you generally should call update() before calling sum(), to
235 * make sure you are not reading stale data.
237 const ValueType& sum() const {
242 * Return the number of data points currently tracked by this
243 * BucketedTimeSeries.
245 * Note that you generally should call update() before calling count(), to
246 * make sure you are not reading stale data.
248 uint64_t count() const {
253 * Return the average value (sum / count).
255 * The return type may be specified to control whether floating-point or
256 * integer division should be performed.
258 * Note that you generally should call update() before calling avg(), to
259 * make sure you are not reading stale data.
261 template <typename ReturnType=double>
262 ReturnType avg() const {
263 return total_.template avg<ReturnType>();
267 * Return the sum divided by the elapsed time.
269 * Note that you generally should call update() before calling rate(), to
270 * make sure you are not reading stale data.
272 template <typename ReturnType = double, typename Interval = Duration>
273 ReturnType rate() const {
274 return rateHelper<ReturnType, Interval>(ReturnType(total_.sum), elapsed());
278 * Return the count divided by the elapsed time.
280 * The Interval template parameter causes the elapsed time to be converted to
281 * the Interval type before using it. For example, if Interval is
282 * std::chrono::seconds, the return value will be the count per second.
283 * If Interval is std::chrono::hours, the return value will be the count per
286 * Note that you generally should call update() before calling countRate(),
287 * to make sure you are not reading stale data.
289 template <typename ReturnType = double, typename Interval = Duration>
290 ReturnType countRate() const {
291 return rateHelper<ReturnType, Interval>(
292 ReturnType(total_.count), elapsed());
296 * Estimate the sum of the data points that occurred in the specified time
299 * The range queried is [start, end).
300 * That is, start is inclusive, and end is exclusive.
302 * Note that data outside of the timeseries duration will no longer be
303 * available for use in the estimation. Specifying a start time earlier than
304 * getEarliestTime() will not have much effect, since only data points after
305 * that point in time will be counted.
307 * Note that the value returned is an estimate, and may not be precise.
309 ValueType sum(TimePoint start, TimePoint end) const;
312 * Estimate the number of data points that occurred in the specified time
315 * The same caveats documented in the sum(TimePoint start, TimePoint end)
316 * comments apply here as well.
318 uint64_t count(TimePoint start, TimePoint end) const;
321 * Estimate the average value during the specified time period.
323 * The same caveats documented in the sum(TimePoint start, TimePoint end)
324 * comments apply here as well.
326 template <typename ReturnType = double>
327 ReturnType avg(TimePoint start, TimePoint end) const;
330 * Estimate the rate during the specified time period.
332 * The same caveats documented in the sum(TimePoint start, TimePoint end)
333 * comments apply here as well.
335 template <typename ReturnType = double, typename Interval = Duration>
336 ReturnType rate(TimePoint start, TimePoint end) const {
337 ValueType intervalSum = sum(start, end);
338 Duration interval = elapsed(start, end);
339 return rateHelper<ReturnType, Interval>(intervalSum, interval);
343 * Estimate the rate of data points being added during the specified time
346 * The same caveats documented in the sum(TimePoint start, TimePoint end)
347 * comments apply here as well.
349 template <typename ReturnType = double, typename Interval = Duration>
350 ReturnType countRate(TimePoint start, TimePoint end) const {
351 uint64_t intervalCount = count(start, end);
352 Duration interval = elapsed(start, end);
353 return rateHelper<ReturnType, Interval>(
354 ReturnType(intervalCount), interval);
358 * Invoke a function for each bucket.
360 * The function will take as arguments the bucket index,
361 * the bucket start time, and the start time of the subsequent bucket.
363 * It should return true to continue iterating through the buckets, and false
364 * to break out of the loop and stop, without calling the function on any
367 * bool function(const Bucket& bucket, TimePoint bucketStart,
368 * TimePoint nextBucketStart)
370 template <typename Function>
371 void forEachBucket(Function fn) const;
374 * Get the index for the bucket containing the specified time.
376 * Note that the index is only valid if this time actually falls within one
377 * of the current buckets. If you pass in a value more recent than
378 * getLatestTime() or older than (getLatestTime() - elapsed()), the index
379 * returned will not be valid.
381 * This method may not be called for all-time data.
383 size_t getBucketIdx(TimePoint time) const;
386 * Get the bucket at the specified index.
388 * This method may not be called for all-time data.
390 const Bucket& getBucketByIndex(size_t idx) const {
391 return buckets_[idx];
395 * Compute the bucket index that the specified time falls into,
396 * as well as the bucket start time and the next bucket's start time.
398 * This method may not be called for all-time data.
403 TimePoint* bucketStart,
404 TimePoint* nextBucketStart) const;
407 * Legacy APIs that accept a Duration parameters rather than TimePoint.
409 * These treat the Duration as relative to the clock epoch.
410 * Prefer using the correct TimePoint-based APIs instead. These APIs will
411 * eventually be deprecated and removed.
413 bool addValue(Duration now, const ValueType& val) {
414 return addValueAggregated(TimePoint(now), val, 1);
416 bool addValue(Duration now, const ValueType& val, uint64_t times) {
417 return addValueAggregated(TimePoint(now), val * ValueType(times), times);
420 addValueAggregated(Duration now, const ValueType& total, uint64_t nsamples) {
421 return addValueAggregated(TimePoint(now), total, nsamples);
423 size_t update(Duration now) {
424 return update(TimePoint(now));
428 template <typename ReturnType = double, typename Interval = Duration>
429 ReturnType rateHelper(ReturnType numerator, Duration elapsedTime) const {
430 return detail::rateHelper<ReturnType, Duration, Interval>(
431 numerator, elapsedTime);
434 TimePoint getEarliestTimeNonEmpty() const;
435 size_t updateBuckets(TimePoint now);
437 ValueType rangeAdjust(
438 TimePoint bucketStart,
439 TimePoint nextBucketStart,
442 ValueType input) const;
444 template <typename Function>
445 void forEachBucket(TimePoint start, TimePoint end, Function fn) const;
447 TimePoint firstTime_; // time of first update() since clear()/constructor
448 TimePoint latestTime_; // time of last update()
449 Duration duration_; // total duration ("window length") of the time series
451 Bucket total_; // sum and count of everything in time series
452 std::vector<Bucket> buckets_; // actual buckets of values